javascript the method by which elements id and name are obtained directly

  • 2020-06-03 05:46:41
  • OfStack

This article illustrates how javascript directly obtains elements from the elements id and name. Share to everybody for everybody reference. The specific analysis is as follows:

We know that some of the third side js libraries simplify how to quickly select elements in html, which may seem like 10 points, but it's not. And js itself comes with a handy way to select specific elements, which is briefly described below.

In html, the most straightforward way to identify the html element is to use the name and id attributes, which differ slightly: id must have only one page, but name can have duplicates.

In js, the id name automatically becomes a property of the window object if it does not have the same name as the built-in property or global variable, as in the topmost environment of an html page:

this === window

So if we write an html element code like this we can refer to it like this:

<input type="button" id="btn_ok" value="Ok" onclick="..." />
// You can quote it like this 
btn_ok.onclick = function(){};
// Or down below 1 The sample of = ...;

For name attributes, only certain types of html element has a similar approach, such as: form, img, iframe, applet, embed, object, etc. Within these elements, elements of a particular name attribute can be accessed through global variables or document attributes; If there are multiple elements of the same name attribute, a read-only array like NodeList is returned, such as the following code:

  <img name="pic" src="#" alt="pic_0" />
  <img name="pic" src="#" alt="pic_1" />
  <img name="pic" src="#" alt="pic_2" />
// We can quote it this way name for pic The elements: 
for(x in pic)
// Or is " standard " grammar each Statements way 
for each(img in pic)

I hope this article has been helpful for your javascript programming.

Related articles: