M
M
Madsh2021-07-04 22:01:14
JavaScript
Madsh, 2021-07-04 22:01:14

Why does the code on Js removeChild not work?

I'm learning JavaScript, I set a task for myself: Using removeChild, remove odd paragraphs from the page, and if the paragraph is even, then the text should turn red. My code:

<body>
    <h1>DOM Examples</h1>
    <div>
        <p>Here is the paragraph</p>
        <p>Here is the second paragraph</p>
        <p>Here is the third paragraph</p>
        <p>Here is the forth paragraph</p>
        <p>Here is the fifth paragraph</p>
        <p>Here is the sixth paragraph</p>
    </div>
    <script>
        var myDiv = document.querySelector('div');
        for (i=0; i<myDiv.length; i++){
            if (i%2==0){
                myDiv.removeChild(myDiv.children[i]);
            }
            else myDiv[i].style.color = "red";
        }
    </script>
</body>


The code doesn't throw errors, but it doesn't do anything either. Why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-07-04
@sergiks

Dealing with the problem, it is worth exploring what is being worked on: what is in myDiv.length- can be output to the console, as an option. What is it - it is worth reading the documentation. An important point: this is a "live" collection. As soon as you remove an element from it, the collection is updated. Removed the 1st, all shifted by 1, and the 3rd will be the one that was previously the 4th. For a task, you can use querySelectorAll - this is a static collection.console.log(myDiv.length); // undefined

spoiler

H
heider, 2021-07-05
@heider

var myP = document.querySelectorAll('div > p');
        for (var i = 0; i < myP.length; i++) {
            if (i % 2 == 0) {
                myP[i].remove();
            }
            else myP[i].style.color = "red";
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question