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.
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).
use document. getElementsByClassName("helloh")[0]. innerText instead of document. getElementsByClassName("helloh").
Document.getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
There are several issues: Class names (and IDs) are not allowed to start with a digit. You have to pass a class to getElementsByClassName() . You have to iterate of the result set.
The syntax is as follows:var elements = document. getElementsByClassName(name); Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.
getElementsByClassName
returns an array of elements. Traverse through that array and get the innerText
property of each. For example:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With