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
ortexts[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
orinnerText
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
3 Answers
Reset to default 6The 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>