Home > Web Front-end > JS Tutorial > body text

JavaScript method to directly obtain elements through element id and name_javascript skills

WBOY
Release: 2016-05-16 16:01:44
Original
1663 people have browsed it

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
Copy after login

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 = ...;
Copy after login

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);
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!