Karan Singh Dhir
Karan Singh Dhir

Reputation: 751

What does quertySelector return null value?

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">

Upvotes: 1

Views: 140

Answers (3)

Pointy
Pointy

Reputation: 413737

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

Upvotes: 5

Ben Temple-Heald
Ben Temple-Heald

Reputation: 708

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');

Upvotes: 1

Sebastian Krysiak
Sebastian Krysiak

Reputation: 911

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">

Upvotes: 2

Related Questions