What's the easiest way to find Dom elements with a css selector, without using a library?
function select( selector ) { return [ /* some magic here please :) */ ] }; select('body')[0] // body; select('.foo' ) // [div,td,div,a] select('a[rel=ajax]') // [a,a,a,a]
This question is purely academical. I'm interested in learning how this is implemented and what the 'snags' are. What would the expected behavior of this function be? ( return array, or return first Dom element, etc ).
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
The easiest way to find an HTML element in the DOM, is by using the element id.
popupbutton is the fastest.
In addition to the custom hacks, in recent browsers you can use the native methods defined in the W3C Selectors API Level 1, namely document.querySelector()
and document.querySelectorAll()
:
var cells = document.querySelectorAll("#score > tbody > tr > td:nth-of-type(2)");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With