DOM / pure JavaScript solution to jQuery.closest() implementation?

后端 未结 8 1850
感动是毒
感动是毒 2020-12-06 00:26

Here\'s the markup i\'m trying to query. So given the markup:

相关标签:
8条回答
  • 2020-12-06 01:07

    function closestById(el, id) {
      while (el.id != id) {
        el = el.parentNode;
        if (!el) {
          return null;
        }
      }
      return el;
    }
    
    // Use it like:
    
    yourTarget = closestById(document.getElementById('unique-identifier'),'targetId')
    alert(yourTarget.id);
    <div id="targetId">
      Finish
      <div>
        <div id="unique-identifier">
          Start
        </div>
      </div>
    </div>

    This searches upwards, until a certain ID is found. You can also alter the code to find certain classes.

    0 讨论(0)
  • 2020-12-06 01:14

    In this case, use JavaScript's closest()

    Exemple:

    var el = document.getElementById('div-03');
    
    var r1 = el.closest("#div-02");  
    // returns the element with the id=div-02
    
    var r2 = el.closest("div div");  
    // returns the closest ancestor which is a div in div, here is div-03 itself
    
    var r3 = el.closest("article > div");  
    // returns the closest ancestor which is a div and has a parent article, here is div-01
    
    var r4 = el.closest(":not(div)");
    // returns the closest ancestor which is not a div, here is the outmost article
    <article>
      <div id="div-01">Here is div-01
        <div id="div-02">Here is div-02
          <div id="div-03">Here is div-03</div>
        </div>
      </div>
    </article>

    You can find more information, on MDN Web Docs by clicking here

    0 讨论(0)
提交回复
热议问题