Home  >  Article  >  Web Front-end  >  How to get DOM elements from HTML more elegantly

How to get DOM elements from HTML more elegantly

autoload
autoloadOriginal
2021-04-07 15:09:211672browse

How to get DOM elements from HTML more elegantly

The DOM in JS is an important part of JavaScript learning. The traditional method of obtaining DOM The method of elements is really too troublesome. How can we get elements from HTML more elegantly? This article will show you how.

1. Use querySelectorAll() method

## Return All elements in the document that match the specified CSS selector

<!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 class="list">
           <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>

   <script>
       const items=document.querySelectorAll(".list .item");
       console.log(items);
   </script>
</body>
</html>

2. Use the querySelector() method

to return the CSS selection that matches the specified CSS selector in the document The first element of the device

<!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 class="list">
           <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>

   <script>
         firstItem = document.querySelector(&#39;.list .item&#39;);
         firstItem.style.background ="yellow";
   </script>
</body>
</html>

Recommended: "

2021 js interview questions and answers (large summary)"

The above is the detailed content of How to get DOM elements from HTML more elegantly. 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