Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text in getElementsByClassName [closed]

Tags:

javascript

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

like image 629
Zac Powell Avatar asked Sep 22 '13 23:09

Zac Powell


People also ask

How do I find the inner text of a class?

use document. getElementsByClassName("helloh")[0]. innerText instead of document. getElementsByClassName("helloh").

What does getElementsByClassName () function return?

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.

Why does document getElementsByClassName not work?

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.

How do you get value using document getElementsByClassName?

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.


1 Answers

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/

like image 191
Jon Newmuis Avatar answered Nov 02 '22 06:11

Jon Newmuis