const span = document.querySelector("span") console.log(span.parentNode); console.log(span.parentElement); console.log(span.parentNode.parentNode);
<body> <!-- beforebegin --> <h3> <!-- afterbegin --> <span class="span">khải lê</span> <span class="span2">kai</span> <!-- beforeend --> </h3> <!-- afterend --> <script src="JS/DOM/TRAVERSING.JS"></script> </body>
It can be done by just logging the innerHTML
property. Like:
const span = document.querySelector("span");
console.log(span.innerHTML);
console.log(span.parentElement.innerHTML);
console.log(span.parentNode.innerHTML);
You can:
const span = document.querySelector("span") console.log(span.parentNode.innerHTML); console.log(span.parentElement.innerHTML); console.log(span.parentNode.parentNode.innerHTML);
<body> <!-- beforebegin --> <h3> <!-- afterbegin --> <span class="span">khải lê</span> <span class="span2">kai</span> <!-- beforeend --> </h3> <!-- afterend --> <script src="JS/DOM/TRAVERSING.JS"></script> </body>
The easiest way to achieve this, is by adding an id to the element you're looking for, and then use the document selector to retrieve the element.
You can try this:
// HTML
<div id="my-div">
<p>Hello World</p>
</div>
// Browser
const elem = document.getElementById('my-div');
console.log(elem)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.