I am trying to get the textContent of a h3 tag that appears above my parent div tag. The code is repeated, and adding an id is not an option for h3 tag. Looking to do this in pure Javascript. My html currently is...
<h3>Some header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
<div id="someid" class="panel-heading"></div> //child
<span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and the value of h3 tag
</div>
<h3>Some other header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
<div id="someid" class="panel-heading"></div> //child
<span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and some other tag when this span button is clicked
</div>
<h3>yet another header</h3> //textContent I am trying to get.
<div class="panel panel-success"> //parent
<div id="someid" class="panel-heading"></div> //child
<span class="pull-right glyphicon glyphicon-list-alt" style="padding-right: 1%"
onclick="myFunc(this.parentNode.id, what.goes.here?)"></span> //this needs to return parent id and yet another header when clicked.
</div>
This piece of code repeats many times, and the textContent of h3 and the div id changes every time. I am trying to return the value of the textContent of the h3 tag that appears about the span button i am clicking relative to the div tag that appears during the click. The h3
tag is not part of any other parent/child relationships, and is stand along...
From the click
handler of the span
you can access the above h3
element like this:
this.parentNode.previousSibling.textContent
See: https://developer.mozilla.org/en/docs/Web/API/Node/previousSibling
document.getElementByID("someid").parentElement.previousElementSibling.textContent;
Edited
let content = document.querySelectorAll('h3');
let count = content.length;
if (count) {
for (let i = 0; i < count; i++) {
alert(content[i].textContent);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.