Home >Web Front-end >JS Tutorial >JavaScript method to directly obtain elements through element id and name_javascript skills
The example in this article describes how JavaScript can directly obtain elements through element id and name. Share it with everyone for your reference. The specific analysis is as follows:
We know that some third-party js libraries have made some simplifications on how to quickly select elements in html. They seem to be very mysterious, but in fact they are not. Moreover, js itself comes with a simple method for selecting special elements. I will briefly introduce it below.
In HTML, the most direct way to identify HTML elements is generally the name and id attributes, which are slightly different: the id must be unique to the page, but the name can be repeated.
In js, if the id name does not have the same name as a built-in attribute or global variable, the name automatically becomes an attribute of the window object, and in the top-level environment of an html page there is:
this === window
So if we write an html element code like the following we can reference it like this:
<input type="button" id="btn_ok" value="Ok" onclick="..." /> //可以这样引用 btn_ok.onclick = function(){}; //或者下面也是一样的 window.btn_ok.style = ...;
For the name attribute, only certain types of html elements have similar methods, such as: form, img, iframe, applet, embed, object, etc. In these elements, elements with specific name attributes can be accessed through global variables or document attributes; if there are multiple elements with the same name attribute, a NodeList-like read-only array object is returned, such as the following code:
<div> <img name="pic" src="#" alt="pic_0" /> <img name="pic" src="#" alt="pic_1" /> <img name="pic" src="#" alt="pic_2" /> </div> //我们可以这样引用name为pic的元素: for(x in pic) console.log(pic[x].alt); //或者是非"标准"语法each语句方式 for each(img in pic) console.log(img.alt);
I hope this article will be helpful to everyone’s JavaScript programming design.