Javascript

js auto selector dom by providing id All In One

本文主要是介绍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


Flag Counter

©xgqfrms 2012-2020

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

原创文章,版权所有©️xgqfrms, 禁止转载

这篇关于js auto selector dom by providing id All In One的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!