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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:48:11  来源:igfitidea点击:

Get text in getElementsByClassName

javascript

提问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

getElementsByClassNamereturns an array of elements. Traverse through that array and get the innerTextproperty 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/