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

creating an element in JavaScript

I have 3 <section> tags in my html file, I’ve created one more <section> element in js

const lastSection = document.createElement('section');

and I saved them all in a variable

const allSections = document.querySelectorAll('section');

the issue is, when I run console.log(allSections.length); it returns only 3.

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

I want an explanation of what’s going in ?

I expected it returns 4;

>Solution :

You have created the element but haven’t append it to any parent container. SO, it doesn’t exist in the html yet. Use appendChild(lastSection) to it’s parent container. Then you’ll have four sections.

const lastSection = document.createElement('section');
document.body.appendChild(lastSection) //append it to the required parent(I've added it to the body for example)
const allSections = document.querySelectorAll('section');
console.log(allSections.length);
<section>1</section>
<section>2</section>
<section>3</section>
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