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

How to get DOM elements from HTML more elegantly

autoload
Release: 2021-04-15 14:01:35
Original
1728 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template