Reputation: 4342
I have been trying to get the text from a div using only javascript.
I started with jQuery using the following code:
var divText = $("div.Xr3").html();
Then for my JavaScript I tried:
var divText = document.getElementsByClassName("Xr3").innerHtml;
Which returns undefined. How can I accomplish this using JavaScript only?
Upvotes: 0
Views: 88
Reputation: 4368
If Xr3
is used one time, you can use
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
Upvotes: 1
Reputation: 198324
getElementsByClassName
returns a live array of HTML elements, so you can't access innerHTML
directly like this. You will either have to loop over its results, or if you know there's only one, apply [0]
to it before accessing innerHTML
.
var divTexts = [];
var divs = document.getElementsByClassName("Xr3");
var numDivs = divs.length;
while (var i = 0; i < numDivs; i++) {
divTexts.push(divs[i].innerHtml);
}
or, in a single-element scenario,
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
Upvotes: 1