*This has to be done in javascript, not jQuery.
What I'm trying to do is grab the innerText
of the h4
tag when <a>
with the class btn-blue
is clicked.
I realize that I could do:
element.parentElement.previousElementSibling.children[0].innerText;
but I'm really wanting something more flexible.
This is what I have so far, and it does work when I run it in the console (chrome), but as soon as I add it to the site, it doesn't pull in the innerText of the h4 tag.
HTML
<div class="border-box clearfix">
<div class="blah">
<h4>h4 Title</h4>
<p>paragraph</p>
</div>
<div class="head clearfix">
<h4>h4 Title</h4>
<p>paragraph</p>
</div>
<p class="float-right">
<a href="/transactions/" class="btn-blue">anchor tag</a>
</p>
</div>
JavaScript
var el = document.getElementsByClassName('head')[0];
var parent = el.parentElement;
while(parent && parent !== document.body && parent.className && parent.className.indexOf('head'){
parent = parent.previousElementSibling;
}
var children = parent.childNodes;
for(i=0; i < children.length; i++){
var name = children[i].tagName;
if(name.toLowerCase() === 'h4'){
var text = children[i].innerText || children[i].textContent;
return text;
}
}
I believe the issue is with using parent.className.indexOf('head')
in the while loop. What I'm trying to determine is if the element has the class of head, and from the SO questions (javascript - Test if an element contains a class), I've seen I can do indexOf to check and see if head is within the class.
I've also read that I can use .classList.contains('head')
, but that doesn't include support for earlier IE browsers.
Two questions:
Am I getting the
innerText
of the<h4>
tag in the best possible way? (this could be better suited for codereview.stackoverflow.com).What the best way to test if a element has a class within a while loop?
SOLUTION:
I ended up using @Greg Burghardt 's solution solely because it was the easiest for me to tweak and implement for use in Google Tag Manager. The final code looked like this:
function(){
var element = {{gtm.element}};
var elementClass = 'border-box';
while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){
element = element.parentNode;
}
return element.querySelector('h4').innerText || element.querySelector('h4').textContent;
}