Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nextSibling returns null while sibling exists

In this part of code, why nextSibling returns null ?

const formIt = () => {
  const titles = document.querySelectorAll('h1');
  document.getElementById('content').innerHTML = '';
  titles.forEach(title => {
    console.log(title.nextSibling);
    let p = title.nextSibling; //Returns null
    let pWrapper = document.createElement('div');
    pWrapper.appendChild(p);
document.getElementById('content').appendChild(pWrapper);
  });
};

formIt();
<div id='content'>
  <h1>...</h1>
  <p>...</p>
  <h1>...</h1>
  <p>...</p>
  <h1>...</h1>
  <p>...</p>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

On line 3 you set the innerHTML of content to an empty string.

That removes all the h1 and p elements from the DOM.

They aren’t siblings after that.

——

Fiddle with innerHTML after you have finished the loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading