Javascript uses the element id and name to directly obtain the element.
This article mainly introduces the method for javascript to directly obtain elements through element id and name. It involves some techniques related to javascript to obtain elements and is very useful. For more information, see
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:
?
So if we write the following html element code, we can reference it like this:
?
1 2 3 4 5 |
<Input type = "button" id = "btn_ OK" value = "OK" onclick = "..."/> // Can be referenced like this Btn_ OK .onclick = function (){}; // Or the following is the same Window. 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:
?
1 2 3 4 5 6 7 8 9 10 11 |
<Div> </Div> // We can reference the element whose name is pic as follows: For (x in pic) Console. log (pic [x]. alt ); // Or non-"standard" Syntax For each (img in pic) Console. log (img. alt ); |
I hope this article will help you design javascript programs.