Several methods of native j to get elements

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
  <div id='div'></div>
  <div class='div'></div>
  <div class='div'></div>
  <div class='div'></div>
  <input type="text" name="hobby">
  <input type="text" name="hobby">
</body>
</html>

1. The method of getting an element by id: document.getElementById('div'

  params: parameters can only be valid id names

  The element obtained by this method returns an element itself object   

  

2. The method of getting elements by class name: document.getElementsByClassName('div')

  params: parameters can only be valid class class names

  The element obtained by this method returns an array, and the array element is the selected element itself

  

3. The method of getting elements by tag name: document.getElementsByTagName('div')

  params: parameters can only be valid tag names

  The element obtained by this method returns an array, and the array element is the selected element itself

   

4. The method of getting elements by name: document.getElementsByName('hobby')

  params: parameters can only be valid name names

  The element obtained by this method returns an array, and the array element is the selected element itself

  

5. Native powerful DOM selector querySelector: document.querySelector(params)

  params: Parameters can be valid selectors: tag, id, class, nested (div>p, .div .p...)

    Select id: document.querySelector('#div') similar to document.getElementsByClassName('div')

    Selection class: document.querySelector('.div') similar to document.getElementsByClassName('div') [0] (the first element of the array)

    Select tags: document.querySelector('div') like document.getElementsByTagName('div') [0] (first element of array)

    Nested selection: document.querySelector('body div')

  The element obtained by this method returns the element itself, only the first element is returned;

6. Native powerful DOM selector querySelectorAll: document.querySelectorAll(params)

  params: Parameters can be valid selectors: tag, id, class, nested (div>p, .div .p...)

    Select id: document.querySelectorAll('#div')[0]  (the first element of the array)   like document.getElementsByClassName('div')

    Selection class: document.querySelectorAll('.div') similar to document.getElementsByClassName('div')  returns an array

    Select tags: document.querySelectorAll('div') like document.getElementsByTagName('div')

    Nested selection: document.querySelectorAll('body div')

  The element obtained by this method returns an array, and the array element is the selected element itself;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324974665&siteId=291194637