Get next element with specific class of clicked element with pure js

前端 未结 3 2082
深忆病人
深忆病人 2021-01-24 04:06

I am trying to get the the first element with a specific class which follow the element clicked with pure JS (no JQuery) in the following way but get el.nextSibling is not a fun

3条回答
  •  猫巷女王i
    2021-01-24 04:42

    You can add a while loop to go searching for the first nextSibling that matches your criteria.

    edit: As @j08691 points out, if your real code only cares about elements and not other node types, you can use nextElementSibling.

    const togglers = document.querySelectorAll('.toggler');
    //console.log(togglers);
    togglers.forEach(function(el) {
      el.addEventListener('click', function(e) {
        var nextSibling = el.nextSibling;
        while (nextSibling) {
            if (
                nextSibling.nodeType == Node.ELEMENT_NODE
             && nextSibling.classList.contains('folder-content')
            ) {
                nextSibling.style.display = 'block';
                break;
            }
            nextSibling = nextSibling.nextSibling;
        }
      })
    });
    Click me 1
    not this
    not this
    not this
    Click me 1.5
    not this
    not this
    not this
    Click me 2
    Click me 3
    no folder content here!

提交回复
热议问题