[英]How can I get the textContent that appears before the parent tag?
我正在嘗試獲取出現在父 div 標簽上方的 h3 標簽的 textContent。 代碼重復,添加id不是h3標簽的選項。 希望在純 Javascript 中執行此操作。 我的 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>
這段代碼重復了很多次,每次h3的textContent和div id都在變化。 我正在嘗試返回關於我單擊的跨度按鈕出現的 h3 標簽的 textContent 值,該值相對於單擊期間出現的 div 標簽。 h3
標簽不是任何其他父/子關系的一部分,而是站在...
從span
的click
處理程序中,您可以像這樣訪問上面的h3
元素:
this.parentNode.previousSibling.textContent
請參閱: https : //developer.mozilla.org/en/docs/Web/API/Node/previousSibling
document.getElementByID("someid").parentElement.previousElementSibling.textContent;
已編輯
let content = document.querySelectorAll('h3');
let count = content.length;
if (count) {
for (let i = 0; i < count; i++) {
alert(content[i].textContent);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.