Home >Web Front-end >JS Tutorial >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('.list .item'); 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!