Reputation: 225
I want to set up a variable which gets the inner text of the second h2 within header tag, any help is appreciated. thank you.
<header>
<h2>I don't need this</h2>
</header>
<header>
<h2>This innertext I need</h2>
</header>
Upvotes: 1
Views: 1469
Reputation: 7105
This function will return the innerText
of the h2
inside the second header
:
function() {
var headerElement = document.getElementsByTagName('header')[1];
var h2Element = headerElement.getElementsByTagName('h2')[0];
var innerText = h2Element.innerText;
console.log('The text you need is: ' + innerText);
return innerText;
}
In addition, assuming that your html code is NOT going to have any other h2
element and you always want to retrieve the same h2
element you can try:
function() {
var h2Element = document.getElementsByTagName('h2')[1];
var innerText = h2Element.innerText;
console.log('The text you need is: ' + innerText);
return innerText;
}
Upvotes: 1