Reputation: 71
Say I have: <a class="helloh" id="helloh">return this value</a>
Basically I want to get the innerText of <a>
tag based on class name.
The problem is when I try: alert(document.getElementsByClassName("helloh").innerText);
it return undefined
but when I try: alert(document.getElementById("helloh").innerText);
it return me they actual value that I want.
Upvotes: 3
Views: 15328
Reputation: 705
var a = document.getElementsByClassName("helloh")[0].textContent;
alert(a);
<a class="helloh" id="helloh">return this value</a>
Upvotes: 1
Reputation: 17170
A new syntax version is document.querySelector()
which will return the first matching element. It saves you having to do getElementsByClassName('name')[0]
From the following:
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh2" id="helloh2">get by Class</a>
You can use:
// by ID
console.log(document.querySelector('#helloh').innerText)
// by Class
console.log(document.querySelector('.helloh2').innerText)
If you want multiple elements, you can use document.querySelectorAll()
:
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh" id="helloh2">get by Class</a>
// get both by Class
console.log(document.querySelectorAll('.helloh'))
Notice the #
and .
You specify classes with .
, IDs by #
, and omit both to search by block elements .
For example, document.querySelectorAll('div')
will return all divs on the page.
You can also use multiple at the same time:
document.querySelectorAll('div .helloh #helloh2')
Upvotes: 3
Reputation: 328
use document.getElementsByClassName("helloh")[0].innerText
instead of document.getElementsByClassName("helloh").innerText
.
When using getElementsByClassName
, you will get array of elements instead of single array unlike getElementById
.
Upvotes: 10