Comprehensive parsing of js selector

  • 2021-07-01 06:09:16
  • OfStack

There are four native JS selectors: getElementById, getElementsByName, getElementsByTagName and getElementsByClassName. I will introduce the usage of these four selectors one by one.

1. getElementById (get elements through ID)

Usage: document. getElementById ("Id"); Id is the id attribute value of the element to get.

2. getElementsByName (Get the element through the name attribute)

Usage: document. getElementsByName ("Name"); Name is the name attribute value of the element to be obtained. This method 1 is generally applicable to submitting form data. When the name attribute is set when the element is form, img, iframe, applet, embed and object, an attribute named after the name attribute value will be automatically created in the Document object. So the corresponding dom object can be referenced through document. domName

3. getElementsByTagName (Get element by element name)

Usage: document. getElementsByTagName (TagName); TagName is the tag name of the element to be obtained. When TagName is *, it means to obtain all elements. document can also be replaced by DOM elements, but only a subset of elements after the DOM element can be obtained.

4. getElementsByClassName (Get elements through the CSS class)

Usage: document. getElementsByClassName (ClassName); ClassName is the name of the CSS class for which the element is to be fetched, separated by a space after each CSS class if multiple elements are to be fetched at the same time. For example, document. getElementsByClassName ("class2 class1") will get class1 and class2 style elements, and document can also be replaced by DOM elements, so that only a subset of elements after the DOM element can be obtained.


<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<body>
<div> I got it through tags </div>
<div id="box"> I was through id Get </div>
<div class="box1"> I was through class Get </div>
<form action="" name="box2">
   I was through name Get 
</form>
</body>
<script type="text/javascript">
  var div = document.getElementsByTagName("div");
  var box = document.getElementById("box");
  var box1 = document.getElementsByClassName("box1");
  var box2 = document.getElementsByName("box2");
</script>
</html>

Related articles: