1

querySelector returns null when searched for the id "#b>a", but getElementById returns the correct element. What's going on?

var x = document.querySelector('#b>a');
console.log(x);
var y = document.getElementById("b>a");
console.log(y);
Name <input type="text" id="b>a">
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Karan Dhir
  • 731
  • 1
  • 6
  • 24

3 Answers3

5

The > character has meaning in CSS selector syntax. You'd have to use "#b\>a".

The > is the "immediate child" combinator, so plain "#b>a" selects an <a> element that's a child of your element with id "b".

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    ... at which point you might as well just use document.getElementById(), unless your use case requires a selector. – BoltClock Aug 09 '17 at 13:23
  • It's called a combinator ;) – BoltClock Aug 09 '17 at 13:24
  • @BoltClock agreed, though using selectors isn't weird or bad or anything, especially in the context of some sort of tooling/framework situation. *edit* yes dang it I was trying to remember the term; in my defense I was typing while on the phone ;) – Pointy Aug 09 '17 at 13:24
  • Indeed, there are numerous situations that require a selector. – BoltClock Aug 09 '17 at 13:25
  • In [HTML 4 IDs](https://www.w3.org/TR/html4/types.html#type-name) could not contain ">", dunno if it was ever enforced though (like IDs starting with a number were illegal but tolerated). – RobG Aug 09 '17 at 13:28
  • @RobG: It was never enforced. #b\>a will match elements with the corresponding id regardless of the doctype. This is precisely why they relaxed the restrictions in HTML5. ([The plural "elements" is not a typo, by the way.](https://stackoverflow.com/questions/7262195/several-elements-with-the-same-id-responding-to-one-css-id-selector/8753329#8753329)) – BoltClock Aug 09 '17 at 13:29
  • 1
    [`CSS.escape()`](https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape) could be useful, since there are other characters as well that need to be escaped within CSS selectors. Mind the [browser compabitiliy](https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape#Browser_compatibility). – vsa Aug 09 '17 at 14:14
2

You need to escape the > character. See snippet below

var x = document.querySelector('#b\\>a');
console.log(x);
var y = document.getElementById("b>a");
console.log(y);
Name <input type="text" id="b>a">
1

Query by selector will look for types before characters, so it will look for an rather than the text a.

To get this to work you would need to escape the selector using

var x = document.querySelector('#b\\>a');
Ben Temple-Heald
  • 708
  • 1
  • 6
  • 16