2017-08-09 110 views
1

querySelector在搜索id「#b> a時返回null,但getElementById返回正確的元素。這是怎麼回事?quertySelector返回空值是什麼?

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

+0

選擇爲什麼你需要,因爲它是高度預計麻煩運行ID這樣的名字? – reporter

回答

5

>字符在CSS選擇器語法意義。你必須使用"#b\>a"

>是「直接子女」組合子,所以普通"#b>a"選擇一個<a>元素,它是您的元素的ID爲「b」的子元素。

+1

...在這種情況下,您可能只需使用document.getElementById(),除非您的用例需要選擇器。 – BoltClock

+0

它被稱爲組合器;) – BoltClock

+0

@BoltClock同意,雖然使用選擇器並不奇怪或不好或什麼都不是,特別是在某種工具/框架情況下。 *編輯*是當它我試圖記住這個詞;在我的防守中,我正在打電話;) – Pointy

2

您需要轉義>字符。請參見下面的代碼片段

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

通過選擇查詢將尋找類型的角色前,所以它會尋找的,而不是文字。

爲了得到這個工作,你需要使用逃生

var x = document.querySelector('#b\\>a');