Thuộc tính nextElementSibling

Thuộc tính nextElementSibling chứa phần tử tiếp theo, nằm trong cùng một phần tử cha. Nếu không có phần tử như vậy - sẽ trả về null.

Cú pháp

javascriptphần_tử.nextElementSibling;

Ví dụ

Cho phần tử #elem. Hãy in ra văn bản của phần tử anh em liền kề phía dưới của nó:

html<p id="elem">elem</p>
<p>sibling</p>
javascriptlet elem = document.querySelector('#elem');
let text = elem.nextElementSibling.textContent;

console.log(text);

Kết quả thực thi mã:

javascript'sibling'

Ví dụ

Nếu không có phần tử anh em liền kề phía dưới hoặc nó không nằm trong phần tử cha của phần tử của chúng ta, cũng sẽ trả về null:

html<div>
  <p id="elem">elem</p>
</div>
<p>sibling</p>
javascriptlet elem = document.querySelector('#elem');
console.log(elem.nextElementSibling);

Kết quả thực thi mã:

javascriptnull

Xem thêm