XVirtusX
XVirtusX

Reputation: 709

How to get textContent from a <img> tag?

I'm working on a greasemonkey script to format some raw numbers by thousands. The format function is just fine. Problem is: some numbers are placed on img tags, for instance:

<div class = "opinion">
    <img class ="icon-like" alt="img" src="like.png">1148597
    <img class="icon-dislike" alt="img" src="dislike.png">600000000
</div>

Since img tags by definition has no child nodes, what is the best way to iterate over the imgs to place the formatted number back on them? If I use .innerHTML, the img tag is removed, displaying just the formatted numbers.

tnx in advance.

Upvotes: 1

Views: 2720

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

Just call nextSibling on the image, then use textContent to actually get the text:

var images = document.querySelectorAll('.opinion img');

Array.prototype.forEach.call(images, function (el) {
    var text = el.nextSibling.textContent;
    // Use the text associated with the image...
});

Here's the fiddle: http://jsfiddle.net/TYGAq/

Upvotes: 3

Related Questions