简体   繁体   中英

javascript equivalent of jquery all children selector

I have the following jquery selector which I am trying to convert to regular javascript.

$("#lelement>*").on("dblclick", function(){
});

what would the equivalent be with regular javascript ? Can I do this ?

document.getElementById('element').childNodes.addEventListener("dblclick", function(e){
});

You'll have to explicitly iterate over all elements which match the #lelement>* selector (the collection can be obtained with querySelectorAll ), and then attach a handler to each of them:

 document.querySelectorAll('#lelement > *').forEach((child) => { child.addEventListener('dblclick', () => console.log('double clicked!')); }); 
 <div id="lelement"> <div>content 1</div> <div>content 2</div> </div> 

Note that NodeList.forEach isn't all that old a method; not all browsers support it. So, for ancient browsers, use a polyfill or Array.prototype.forEach instead:

 Array.prototype.forEach.call( document.querySelectorAll('#lelement > *'), (child) => { child.addEventListener('dblclick', () => console.log('double clicked!')); } ); 
 <div id="lelement"> <div>content 1</div> <div>content 2</div> </div> 

It would be the exact same selector, just passed to document.querySelectorAll() .

document.querySelectorAll("#element > *");

Then, you would enumerate the found nodes and manually set each up with an event handler. Since .querySelectorAll() returns a node list, it's best to convert that to an Array so that the Array.forEach() method can be reliably called in all browsers.

 let elems = Array.prototype.slice.call(document.querySelectorAll("#element > *")); elems.forEach((el) => { el.addEventListener("dblclick", function(){ console.log("You clicked me!"); }); }); 
 <div id="element"> <h1>Some Heading</h1> <p>Some Paragraph</p> <div>Some Div</div> </div> 

One elegant, non-jQuery way to do this would be via querySelectorAll() :

  document.querySelectorAll('#lelement > *').forEach(function(node) { node.addEventListener("dblclick", function(e){ console.log('double clicked on child of #element'); }); }) 
 p { margin:1rem; background:red; color:white; } 
 <div id="lelement"> <p>Double click me - Child 1</p> <p>Double click me - Child 2</p> </div> 

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