Home  >  Article  >  Web Front-end  >  How to get DOM elements in HTML using traditional methods

How to get DOM elements in HTML using traditional methods

autoload
autoloadOriginal
2021-04-07 14:44:151952browse

How to get DOM elements in HTML using traditional methods

The DOM in JS is an important part of JavaScript learning,# The acquisition of ##DOM elements is an important bridge between HTML and JS. This article will take you to take a look at the traditional way of obtainingDOM element.

1.getElementById() method Returns a reference to the first object with the specified id

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
       <ul id="list" onclick="getValue()>
           <li class="item">item1</li>
           <li class="item">item2</li>
           <li class="item">item3</li>
           <li class="item">item4</li>
           <li class="item">item5</li>
       </ul>
 </body>
</html>
<script>
function getValue()
  {
  var x=document.getElementById("id")
  alert(x.innerHTML)
  }
</script>
 </script>

2.getElementsByName() method Returns a collection of objects with the specified name.

<!DOCTYPE html>
<html>
<body>
       <ul >
           <li class="item" name="item">item1</li>
           <li class="item" name="item">item2</li>
           <li class="item" name="item">item3</li>
           <li class="item" name="item">item4</li>
           <li class="item" name="item">item5</li>
       </ul>
 </body>
</html>
<script>

  var x=document.getElementsByName("item");
  alert(x.length);
 
 </script>

3.getElementsByTagName() method

Returns a collection of objects with the specified tag name.

<!DOCTYPE html>
<html>
<body>
       <ul >
           <li >item1</li>
           <li >item2</li>
           <li >item3</li>
           <li >item4</li>
           <li >item5</li>
       </ul>
 </body>
</html>
<script>

  var x=document.getElementsByTagName("li");
  alert(x.length);
 
 </script>
Recommended: "

2021 js interview questions and answers (large summary)

"

The above is the detailed content of How to get DOM elements in HTML using traditional methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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