如何从<img/>标签获取textContent?

时间:2013-01-15 23:02:54

标签: javascript dom

我正在使用greasemonkey脚本来格式化一些原始数字。格式功能很好。问题是:有些数字放在img标签上,例如:

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

由于定义has no child nodes的img标签,迭代imgs以将格式化的数字放回到它们上的最佳方法是什么?如果我使用.innerHTML,则删除img标记,仅显示格式化的数字。

提前tnx。

1 个答案:

答案 0 :(得分:3)

只需在图片上调用nextSibling,然后使用textContent实际获取文字:

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...
});

这是小提琴:http://jsfiddle.net/TYGAq/