When to use the `#` symbol to get a DOM element?

天涯浪子 提交于 2020-07-13 00:25:47

问题


Sometimes I need to get elements like this:

var object = document.getElementById('ObjectName');

And sometimes like this:

var object = document.getElementById('#ObjectName');

What’s the difference between them?


回答1:


No, you don't see

var object = document.getElementById('#ObjectName');

You don't see that because that would mean the id of the element starts with # and HTML4 id could only start "with a letter ([A-Za-z])".

What you see is sometimes people using the jQuery library in which the query language allows you to find an object using

var elem = $('#objectId');

And in the future you'll see more and more people using a similar query language with querySelector or querySelectorAll.




回答2:


The # is part of the ID selector in CSS. There are libraries and methods which support CSS selectors for selecting elements, such as jQuery and the native DOM methods querySelector and querySelectorAll.

But in "traditional" DOM method, the # has no special meaning. getElementById('#ObjectName') would select an element which literally has the ID #ObjectName, i.e. <div id="#ObjectName">.




回答3:


The former gets an element with id="ObjectName". The latter gets an element with id="#ObjectName".

In the context of a Selector (as used, for example, by CSS and document.querySelector but not with getElementById) the # character indicates that the text following it is an id.

document.querySelector('ObjectName') (using a type selector) would get <ObjectName /> (not valid HTML) while document.querySelector('#ObjectName') would get an element with id="ObjectName".




回答4:


'#ObjectName'

JQuery (EDIT: or other JavaScript Libraries)

'ObjectName'

DOM (getElementById)



来源:https://stackoverflow.com/questions/15486154/when-to-use-the-symbol-to-get-a-dom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!