Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find DOM elements with css selectors

Tags:

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

like image 257
Stefan Avatar asked May 20 '09 08:05

Stefan


People also ask

What is the best way to locate an element in the DOM?

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.

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.

What is the fastest way to select elements by using CSS selectors?

popupbutton is the fastest.


1 Answers

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)"); 
like image 106
miek Avatar answered Sep 18 '22 11:09

miek