I have seen and avoided code like this:
<div id="myDiv" onClick="alert('hi!');">Div</div>
<script>
myDiv.click(); // <-- this bit seems wrong
</script>
It just seems wrong to me that I should refer to the node by it's id alone without explicitly assigning it to a variable first. Like this:
var myDiv = document.getElementById('myDiv');
Is there a good reason why we shouldn't use code like in the first example or am I just superstitious?
It's bad practice to use the identifiers from the page without specifying where they come from.
The identifiers are "magically" created as properties in the document object. If you use those, it's not clearly apperent how they got there in the first place. If you rename the element, the same Javascript code now creates a global variable instead, and it's hard to see by looking at the code what it was supposed to do, and why it's not working any more.
Also there is a risk for conflicts. If you create a global variable with the same name as the element id, then it will shadow the element and you can no longer reach it.
By using getElementById
the code clearly says that there should be an element with that id in the page, and it also only looks for an element so the risk for naming conflicts is less.
Thanks to Bergi and Pete for links to useful information on this topic.
From these I have gleaned there are few main reasons why this is bad practice:
First of all, it is a bad practice since the maintenance of such code will be very difficult, consider that the script
is not located next to the element or even not in the same file.
Moreover, using id
s in general is not recommended when your HTML page/app grows. The id
attribute must remains unique and you may find it hard to follow it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.