Lấy ra các element có trong DOM thông qua các phương thức của đối tượng document.
ID
Cú pháp: document.getElementById('id')
Giá trị trả về: HTMLElement
Giả sử có đoạn code HTML dưới:
<h1 id="heading-1">Heading 1</h1>Lấy ra thẻ <h1> có id là heading-1:
const headingElement = document.getElementById("heading-1")
console.log(headingElement) // <h1 id="heading-1">Heading 1</h1>Class Name
Cú pháp: document.getElementsByClassName('className')
Giá trị trả về: HTMLCollection
Info
Phương thức này trả về một đối tượng có kiểu là
HTMLCollectiongồm nhiều phần tử.HTMLCollectioncó bản chất là một mảng và không có các phương thức nhận vào callback chẳng hạn nhưmap,filter, …Có thể dùng kỹ thuật mượn hàm để sử dụng các phương thức trên. Xem thêm call Method in JS.
Giả sử ta có một danh sách đơn giản sau:
<ul>
<li class="list-item">List item 1</li>
<li class="list-item">List item 2</li>
<li class="list-item">List item 3</li>
</ul>Lấy ra các thẻ <li> có class là list-item:
const listItemElement = document.getElementsByClassName("list-item")
console.log(listItemElement) // HTMLCollection(3) [li.list-item, li.list-item, li.list-item]By Tag Name
Cú pháp: document.getElementsByTagName('tagName')
Giá trị trả về: HTMLCollection
Cũng ví dụ trên, ta lấy ra các thẻ <li> từ DOM tree:
const liTagElement = document.getElementsByTagName("li")
console.log(liTagElement) // HTMLCollection(3) [li.list-item, li.list-item, li.list-item]CSS Selector
Cú pháp: document.querySelector('selector')
Giá trị trả về: HTMLElement
Attention
Phương thức
querySelectorchỉ chọn một element đầu tiên nếu có nhiều element match.
Giả sử ta có một thẻ <div> chứa một thẻ <h1> và hai thẻ <p>:
<div>
<h1>Heading 2</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<p>
Deserunt, quibusdam laboriosam sit ducimus nemo iste ea recusandae tempora voluptates minima qui
ad, repellat dolores ut, veniam optio reiciendis quod natus!
</p>
</div>Lấy ra thẻ <p> đầu tiên bên trong thẻ <div>:
const firstParagraph = document.querySelector("div p:nth-of-type(1)")
console.log(firstParagraph) // <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>Để chọn nhiều element dựa vào CSS selector thì sử dụng document.querySelectorAll('selector').
HTML Collection
Một số tag chẳng hạn như <form> hoặc <a> thuộc về lớp Document và có thể truy cập thông qua đối tượng document mà cụ thể là document.forms hoặc document.anchors.
Thuộc tính document.forms sẽ trả về mảng các tag <form> có trong HTML. Nếu các tag này có thuộc tính id, có thể xem id đó là key và truy cập thông qua key.
Chẳng hạn ta có một tag <form> có id là form-1:
<form id="form-1">This is a form</form>console.log(document.forms["form-1"]) // <form id="form-1">This is a form</form>Nếu id có thể dùng đặt cho tên biến trong JS, thì không cần sử dụng ngoặc vuông:
<form id="formOne">This is a form</form>console.log(document.forms.formOne) // <form id="formOne">This is a form</form>Tip
Các giá trị trả về của phương thức
getElementById()vàquerySelector()là các đối tượng thuộc lớpHTMLElementkế thừa từElement, ta có thể gọi tiếp các phương thức trên để lấy ra các element con bên trong chúng.
Closest
Phương thức element./closest(selector) được dùng để truy vấn đến element cha của một element nào đó với selector cho trước:
Giả sử chúng ta có đoạn code HTML dưới đây:
<article class="card">
<p>Card name</p>
</article>Đứng từ element <p>, ta vẫn có thể truy vấn được các elements cha của nó:
const pElement = document.querySelector('.card p')
const cardElement = pElement.closest('.card')
const bodyElement = pElement.closest('body')
console.log([cardElement]) // [article.card]
from [[Get a DOM Element]]
sort file.ctime asc