[英]How can I get the textContent that appears before the parent tag?
I am trying to get the textContent of a h3 tag that appears above my parent div tag.我正在尝试获取出现在父 div 标签上方的 h3 标签的 textContent。 The code is repeated, and adding an id is not an option for h3 tag.代码重复,添加id不是h3标签的选项。 Looking to do this in pure Javascript.希望在纯 Javascript 中执行此操作。 My html currently is...我的 html 目前是...
<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.这段代码重复了很多次,每次h3的textContent和div id都在变化。 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.我正在尝试返回关于我单击的跨度按钮出现的 h3 标签的 textContent 值,该值相对于单击期间出现的 div 标签。 The h3
tag is not part of any other parent/child relationships, and is stand along... h3
标签不是任何其他父/子关系的一部分,而是站在...
From the click
handler of the span
you can access the above h3
element like this:从span
的click
处理程序中,您可以像这样访问上面的h3
元素:
this.parentNode.previousSibling.textContent
See: https://developer.mozilla.org/en/docs/Web/API/Node/previousSibling请参阅: https : //developer.mozilla.org/en/docs/Web/API/Node/previousSibling
document.getElementByID("someid").parentElement.previousElementSibling.textContent; 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);
}
}
https://jsfiddle.net/2kk49yLp/1/ https://jsfiddle.net/2kk49yLp/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.