Home > Mobile >  Why can't I use querySelector on a parentElement which I know has the queried class
Why can't I use querySelector on a parentElement which I know has the queried class

Time:09-28

I can traverse to reach my target element like this:

this.parentElement.parentElement.style.backgroundColor = 'red';

But why does this not work even though I know for a fact that the second parentElement has the .container class:

 this.parentElement.parentElement.querySelector('.container').style.backgroundColor = 'red';

Shouldn't .querySelector start the search from the current element?

Example code:

document.querySelectorAll('button').forEach(btn => {

            btn.addEventListener('click', function(){

                //works:
                //this.parentElement.parentElement.style.backgroundColor = 'red';

                //error Cannot read properties of null:
                this.parentElement.parentElement.querySelector('.container').style.backgroundColor = 'red';

            })
            
        });
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        body{
            display: flex;
            flex-direction: row;
        }

        .container{
            width: 25vw;
            border-radius: 1rem;
            background-color: bisque;
            padding: 1rem;
            margin: 1rem;
        }

      
    </style>

</head>
<body>

    
    <div >

        <h2>Element</h2>
        <div >
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam magnam delectus a animi fugit, odio veritatis maxime nihil totam earum, voluptates facere dolores facilis exercitationem? Hic repudiandae optio totam doloribus.</p>
        <button>Color</button>
        </div>
    </div>

        <div >

            <h2>Element</h2>
            <div >
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam magnam delectus a animi fugit, odio veritatis maxime nihil totam earum, voluptates facere dolores facilis exercitationem? Hic repudiandae optio totam doloribus.</p>
            <button>Color</button>
            </div>
        </div>
            <div >

                <h2>Element</h2>
                <div >
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam magnam delectus a animi fugit, odio veritatis maxime nihil totam earum, voluptates facere dolores facilis exercitationem? Hic repudiandae optio totam doloribus.</p>
                <button>Color</button>
                </div>

            </div>
            
</body>
</html>

CodePudding user response:

No. from docs:

The querySelector() method of the Element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.

  • Related