簡體   English   中英

在不使用jQuery的情況下獲取具有類名稱的下一個元素

[英]Get next element with a class name without using jquery

我無權訪問jquery。 我正在嘗試實現手風琴,但是content元素不是緊隨標題之后。 它類似於以下內容:

<div class="header">...</div>
  <div>
    <div class="content">

因此,我添加了一個函數來處理標題上的onclick事件,然后需要獲取具有內容類的HTML源代碼中的下一個元素。 我該如何實現?

您可以在單擊的標頭節點上使用querySlector實現此目的

<div class="header">
  <div>
    <div class="content">


[].forEach.call(document.querySelectorAll('.header'), function(header) {
    header.addEventListener('click', function(e) {
        var content = this.querySelector('.content');
        // here, "this" is the header div, and "content" is the content div
        // do majick accordion things here
    });
});

如何使用遞歸函數和nextSibling [獲取下一個元素(不是子元素)]

<div class="header" onclick="hasClass(this)">...</div>
  <div>
    <div class="content"></div>
  </div>
<script>
function hasClass(e){
    if(e.nextSibling.children === undefined || e.nextSibling.children.length == 0){
        hasClass(e.nextSibling); //go next till find class
    }
    else{
    if(e.nextSibling.children[0].className == "content"){
        console.log(e.nextSibling.innerHTML);  //get class content html
    }
    }
}
</script>

你可以通過

var contentDiv= document.getElementsByClassName("content");

試試這個document.getElementById(header).getElementsByClassName('content');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM