简体   繁体   中英

Fetching DOM with help of pure JavaScript

I have this code:

$("#popupShapes ul li a").click(function () {
     //some code
});

I want to convert it to pure javascript.

This not works because getElementById expects to single id:

document.getElementById('popupShapes ul li a')

How can I convert the jQuery code above to JavaScript?

Use querySelector instead, which accepts a selector string:

document.querySelector("#popupShapes ul li a").addEventListener('click', function () {
     //some code
});

If you have multiple matching elements, use querySelectorAll instead:

for (const a of document.querySelectorAll("#popupShapes ul li a")) {
  a.addEventListener('click', function () {
     //some code
  });
}

You can also use event delegation instead, but this will sometimes result in different behavior than your original code:

document.querySelector('#popupShapes').addEventListener('click', (e) => {
  if (!e.target.matches('#popupShapes ul li a')) return;
  // some code
});
$("#popupShapes ul li a").click(function () {
  //some code
});

I would consider delegation:

 document.getElementById("popupShapes").addEventListener("click", function(e) { const tgt = e.target; if (tgt.matches('#popupShapes ul li a')) { e.preventDefault(); console.log(tgt.href) } else console.log(tgt.tagName,"not interesting click") })
 #popupShapes { background-color: teal; padding:1em; }
 <div id="popupShapes"> <ul> <li><a href="x1">X1</a></li> <li><a href="x2">X2</a></li> </ul> <a href="z1">z1</a> </div>

You would have written in this way.

const nav = document.querySelectorAll('#popupShapes li a')

nav.forEach((item) => {
    item.addEventListener('click', (e) => {
      console.log('hi', e);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM