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.
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>