mcmwhfy mcmwhfy - 3 months ago 7
Javascript Question

what is the difference between two similar javascript selectors

What is the difference of this two selectors:

function myFunction() {
var x = document.querySelectorAll("#srow .cell");
console.log(x[1]);
}
myFunction();


and

function myFunction() {
var x = document.getElementById("srow").querySelectorAll(".cell");
console.log(x[1]);
}
myFunction();


both return the second element

Answer

They are similar but perform different things.

  • The first case returns all elements with class .cell which has at least one parent that has an id srow.
  • The second case gets one of all elements with id srow then returns all child elements with class .cell.

Here is an example that demonstrate their differences: https://jsfiddle.net/1m3k3gzL/

Although HTML5 explicitly prohibits repeated ids, typical browsers usually allow this kind of things to happen.

Comments