Javascript uses the element id and name to directly obtain the element. javascriptname
This example describes how to use javascript to directly retrieve elements by element id and name. Share it with you for your reference. The specific analysis is as follows:
We know that some third-party js libraries have simplified how to quickly select elements in html. It seems like they are not easy to understand. In addition, js itself comes with a simple Selection Method for special elements. The following is a brief introduction.
In html, the most direct identification of html elements is the name and id attributes. The two are slightly different: the id must be unique on the page, but the name can be repeated.
In js, if the id name is not the same as the built-in attribute or the global variable name, the name will automatically become the attribute of the window object. In the top-level environment of an html page, there are:
this === window
So if we write the following html element code, we can reference it like this:
<Input type = "button" id = "btn_ OK" value = "OK" onclick = "... "/> // You can reference btn_ OK .onclick = function () {}; // or the same window is shown below. btn_ OK .style = ...;
For the name attribute, only some types of html elements have similar methods, such as form, img, iframe, applet, embed, and object. You can use global variables or document attributes to access the elements of a specific name attribute. If multiple elements have the same name attribute, return an object similar to a read-only array of NodeList, for example, the following code:
<Div> </div> // You can reference an element whose name is pic as follows: for (x in pic) console. log (pic [x]. alt); // or non-"standard" syntax. log (img. alt );
I hope this article will help you design javascript programs.