Home > Net >  I'm working with JavaScript (DOM), and I can't console log my innerHTML directly in my bro
I'm working with JavaScript (DOM), and I can't console log my innerHTML directly in my bro

Time:10-28

here is my problem here is my problem

what it should be what it should be

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
  • Related