我正在编写一个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>
根据定义,img 标签 has no child nodes ,迭代 imgs 以将格式化数字放回其上的最佳方法是什么?如果我使用 .innerHTML,img 标签将被删除,仅显示格式化的数字。
提前tnx。
最佳答案
只需调用 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...
});
这是 fiddle :http://jsfiddle.net/TYGAq/
关于javascript - 如何从 <img> 标签获取文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14348553/