xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js auto selector dom by providing id All In One

js auto selector dom by providing id All In One

there’s a global variable named by id that references the element

<button id="btn">Subscribe</button>

<script>
  // auto selector by id ✅
  btn.addEventListener('click', () => {
    console.log('click btn');
  });
  let click = new Event("click");
  btn.dispatchEvent(click);
</script>

<button id="btn">Subscribe</button>

<script>
  // querySelector
  const btn = document.querySelector(`#btn`);
  btn.addEventListener('click', () => {
    console.log('click btn');
  });
  let click = new Event("click");
  btn.dispatchEvent(click);
</script>


demo

Chrome

Safari

closest

closest(selectors);

<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>

const el = document.getElementById('div-03');

// the closest ancestor with the id of "div-02"
console.log(el.closest('#div-02')); // <div id="div-02">

// the closest ancestor which is a div in a div
console.log(el.closest('div div')); // <div id="div-03">

// the closest ancestor which is a div and has a parent article
console.log(el.closest("article > div")); // <div id="div-01">

// the closest ancestor which is not a div
console.log(el.closest(":not(div)")); // <article>

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

css parent selector ?

:has pseudo selector

https://matthiasott.com/notes/css-has-a-parent-selector-now

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

refs

https://javascript.info/searching-elements-dom#document-getelementbyid-or-just-id



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-07-08 00:18  xgqfrms  阅读(38)  评论(1编辑  收藏  举报