最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to retrieve the text node for each item in a HTMLCollection? - Stack Overflow

programmeradmin2浏览0评论

having a hard time to get this done. I have the following:

<p class='abc'>text 1</p>
<p class='abc'>text 2</p>

Then I tried something like:

var texts = document.getElementsByClassName('abc');

for(var i=0;i < texts.length; i++){
   console.log(texts[i].text);
}

but it doesn't work. Also tried with Jquery but to no avail.

having a hard time to get this done. I have the following:

<p class='abc'>text 1</p>
<p class='abc'>text 2</p>

Then I tried something like:

var texts = document.getElementsByClassName('abc');

for(var i=0;i < texts.length; i++){
   console.log(texts[i].text);
}

but it doesn't work. Also tried with Jquery but to no avail.

Share Improve this question asked Aug 7, 2015 at 14:17 XVirtusXXVirtusX 7093 gold badges12 silver badges30 bronze badges 5
  • 1 texts[i].innerText or texts[i].innerHTML ? – DontVoteMeDown Commented Aug 7, 2015 at 14:18
  • when is the javascript called relative to the html? – Daniel A. White Commented Aug 7, 2015 at 14:18
  • 1 textContent or innerText depending on browser – CodingIntrigue Commented Aug 7, 2015 at 14:23
  • could you guys stop downvoting questions? jeez... it was a legit doubt. – XVirtusX Commented Aug 7, 2015 at 14:23
  • .innerHTML works. Tnx! – XVirtusX Commented Aug 7, 2015 at 14:24
Add a ment  | 

3 Answers 3

Reset to default 6

The property you're looking for is textContent:

var texts = document.getElementsByClassName('abc');

for(var i=0;i < texts.length; i++){
   console.log(texts[i].textContent);
}

However, older IE versions only support a non-standard innerText attribute, so you might need to fall back to that:

var texts = document.getElementsByClassName('abc');

for(var i=0;i < texts.length; i++){
   console.log(texts[i].textContent || texts[i].innerText);
}

If you are using jQuery, it's text():

$(".abc").each(function() {
    console.log($(this).text());
});

You've almost got it.

Instead of:

console.log(texts[i].text);

You want:

console.log(texts[i].innerHTML);

you need to use .textContent.

var texts = document.getElementsByClassName('abc');
for(var i=0;i < texts.length; i++){
   alert(texts[i].textContent);
}
<p class='abc'>text 1</p>
<p class='abc'>text 2</p>

发布评论

评论列表(0)

  1. 暂无评论