Home > Article > Web Front-end > A simple way to select DOM elements using JS
JSA simple method to select DOM elements. This article summarizes the various methods of js to select DOM, which can be used to learn js knowledge~ ~
Methods for selecting document elements:
1. Select elements by ID (getElementById)
1 ) Usage: document.getElementById("domId")
Among them, domId is the id attribute value of the element to be selected
2) Compatibility: lower than IE8 version The IE browser's implementation of the getElementById method does not distinguish between upper and lower case of the element ID number, and will return elements matching the name attribute.
2. Select elements by name (getElementsByName)
1) Usage method: document.getElementsByName("domName")
Among them, domName is the name attribute value of the element to be selected
2) Description: a. The return value is a nodeList collection (different from Array)
b . Unlike the ID attribute, the name attribute is only valid in a few DOM elements (form form, form element, iframe, img). This is because the name attribute was created to facilitate submitting form data.
c. When setting the name attribute for form, img, iframe, applet, embed, and object elements, an attribute named after the name attribute value will be automatically created in the Document object. Therefore, the corresponding dom object can be referenced through document.domName
3) Compatibility: Elements with matching ID attribute values in IE will also return
3. Select elements by tag name (getElementsByTagName)
1) Usage method: element.getElementsByTagName("tagName")
Among them, element is a valid DOM element (including document)
tagName is the tag name of the DOM element
2) Description: a. The return value is a nodeList collection (difference in Array)
b. This method can only select descendant elements of the element that calls this method.
c. tagName is not case-sensitive
d. When tagName is *, it means selecting all elements (subject to rule b.)
e. HTMLDocument will define some shortcut attributes to access tag nodes. For example: the images, forms, and links attributes of document point to the collection of ,