javascript 在 getElementsByClassName 中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18949817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text in getElementsByClassName
提问by Zac Powell
I am writing some javascript to be run in a bookmarklet that should get the text within a element that has a certain class name.
我正在编写一些要在书签中运行的 javascript,该书签应该在具有特定类名的元素中获取文本。
So for example
所以例如
document.getElementsByClassName('price')
where the web page has or example
网页的位置或示例
<span class="price">
£23
</span>
How would I go about getting the actual text within the the element that has a class name price (i.e £23 in the above example).
我将如何在具有类名价格的元素中获取实际文本(即上面示例中的 £23)。
回答by Jon Newmuis
getElementsByClassName
returns an array of elements. Traverse through that array and get the innerText
property of each. For example:
getElementsByClassName
返回一个元素数组。遍历该数组并获取innerText
每个数组的属性。例如:
var priceEls = document.getElementsByClassName("price");
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
alert("Price: " + price);
}
Live demo: http://jsfiddle.net/YQsBW/
现场演示:http: //jsfiddle.net/YQsBW/