-1

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;

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 1
    Well, you have created the new section, but never add it to the HTML. Select the parent element of sections and use `appendChild` to append the new section to the last line. – Engin Nov 27 '22 at 16:20

1 Answers1

0

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>
Rocky Barua
  • 512
  • 1
  • 4
  • 17