2017-08-05 157 views
0

鑑於111是一個有效的HTML id屬性還是document.querySelector()和document.querySelectorAll()正確地引發語法錯誤?

const div = document.createElement("div"); 
 

 
div.id = 111; 
 

 
document.body.appendChild(div); 
 

 
try { 
 
    console.log(document.querySelector("#111")); 
 
} catch(e) { 
 
    console.error(e); 
 

 
    /* 
 
    Chromium: 
 

 
    DOMException: Failed to execute 'querySelector' on 'Document': 
 
    '#111' is not a valid selector. 
 

 
    Firefox 
 
    SyntaxError: '#111' is not a valid selector 
 

 
    */ 
 
} 
 

 
try { 
 
    console.log(document.querySelectorAll("#111")); 
 
} catch(e) { 
 
    console.error(e); 
 

 
    /* 
 
    Chromium: 
 

 
    DOMException: Failed to execute 'querySelector' on 'Document': 
 
    '#111' is not a valid selector. 
 

 
    Firefox 
 
    SyntaxError: '#111' is not a valid selector 
 

 
    */ 
 
}

然而,document.getElementById()返回元素

const div = document.createElement("div"); 
 

 
div.id = 111; 
 

 
document.body.appendChild(div); 
 

 
try { 
 
    console.log(document.getElementById("111")); 
 
} catch(e) { 
 
    console.error(e); 
 
}

參考文獻:

6.2 SGML basic types

IDNAME令牌必須以字母開頭([A-ZA-Z])和之後可以是任何數量的字母,數字([0-9]) ,連字符(「 - 」), 下劃線(「_」),冒號(「:」)和句點(「。」)。

7.5.2 Element identifiers: the id and class attributes

屬性定義

ID =名[CS]該屬性分配一個名稱的元素。該名稱 在文檔中必須是唯一的。

DOM - Living Standard

儘管本說明書定義了類,ID,和槽的任何元件上 屬性的要求,它沒有如權利要求所給 是否使用它們是符合與否。

HTML - Living Standard

id屬性指定其元素的unique identifier (ID)

身份證可以採取何種形式沒有其他限制;在 具體地,ID可以包括只是數字,以數字開頭,以下劃線開頭 ,由剛標點符號等

Document.querySelector()

拋出異常SYNTAX_ERR如果指定的組的選擇器是 無效。

Document.querySelectorAll()

拋出異常SYNTAX_ERR如果指定的選擇符的組是 無效。


"111"有效的HTML id屬性或者document.querySelector()document.querySelectorAll()正確拋出語法錯誤?

+0

可能重複[什麼是HTML中的id屬性的有效值?](https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in- html) – Thilo

+1

CSS比HTML5更嚴格,請參閱鏈接的副本。 – Thilo

+0

ID和名稱標記必須以字母([A-Za-z])開頭,後面可以跟隨任意數量的字母,數字([0-9]),連字符(「 - 」),下劃線(「_」 ),冒號(「:」)和句點(「。」)。正如你所看到的規則,把它改爲以字母開頭,而不是以數字開頭,然後試試 – Thennarasan

回答

2

根據MDN有關HTML id屬性:

此屬性的值不能包含空格(空格,製表符等)。

這似乎是唯一的限制。他們注意到HTML4更嚴格,但就是這樣。

按照spec

值不能包含任何ASCII空格。

這意味着111是HTML id屬性的有效值。

querySelectorquerySelectorAll但是使用CSS選擇器,這是更嚴格:

ID selector#,其次是有效identifier

在CSS中,標識符(包括元素名,類和在選擇器的ID)只能包含字符[A-ZA-Z0-9]和ISO 10646個字符U + 00A0和更高的,再加上連字符( - )和下劃線(_); 它們不能以數字,兩個連字符或連字符後跟數字開頭。標識符也可以包含轉義字符和任何ISO 10646字符作爲數字代碼(參見下一項)。例如,標識符「B & W?」可寫成「B \ & W \?」或「B \ 26 W \ 3F」。

這意味着#111不是有效的CSS選擇器。相反,使用:

document.querySelector('[id="111"]') 

直接回答你的問題:

"111"有效的HTML id屬性或者是document.querySelector()document.querySelectorAll()正確拋出語法錯誤?

"111"是一個有效的屬性,語法錯誤被正確地拋出。

相關問題