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

1
  • 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. Commented Nov 27, 2022 at 16:20

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.