Jason
Jason

Reputation: 651

What is the difference between the following two statements using the querySelectorAll()?

If I use the following javascript function with CSS selector value of "#game  .screen.active" as argument

var activeScreen = document.querySelectorAll("#game  .screen.active")[0];

The above statement will assign to the activeScreen variable the document element with
id="game" and class="screen" which is currently an active screen.

I have the following question :
1. Is that true, that there will be only one active screen at any point in time?
2. If you provide more than one CSS selectors as argument to the querySelectorAll() function,
do we have to seperate them using comma(',') like the below statement?

var activeScreen = document.querySelectorAll("#game,  .screen.active")[0];

What is the difference between the above two statements, one with the comma and one without
the comma?


The Structure of my index.html

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Game</title>

    <link rel="stylesheet" href="styles/main.css" />
    <script src="scripts/gameEngine.js"></script>
</head>
<body>
    <div id="game">
        <div class="screen" id="splash-screen">
            <h1 class="logo">Ninja <br/>Warrior</h1>
            <span class="continue">Click to continue</span>
        </div>
        <div class="screen" id="main-menu"></div>
        <div class="screen" id="game-screen"></div>
        <div class="screen" id="high-scores"></div>    
    </div>
</body>
</html>

Upvotes: 1

Views: 68

Answers (2)

Marcus Parsons
Marcus Parsons

Reputation: 1803

When using querySelectorAll, you can specify multiple selectors by using the comma , inside of it. Separating ids, class names, element names, etc. with a space is descendant selection.

So, by using #game .screen.active, you are saying target #game's child element(s) that have the class screen and have the class active. So, you could be targeting multiple elements, but they would not include the #game element.

But, by using #game, .screen.active you are targeting both the #game element and any element with both classes screen and active.

Refer to this article from the Mozilla Developer Network about combinators and selectors

Upvotes: 1

Lu&#237;s Soares
Lu&#237;s Soares

Reputation: 6222

Is that true, that there will be only one active screen at any point in time?

Not necessarily. You could have more and they'd be selected with that class. You have control over it (but avoid repeated ids).

If you provide more than one CSS selectors as argument to the querySelectorAll() function, do we have to seperate them using comma(',') like the below statement?

Yes

  • #game .screen.active means: get me anything with the classes .screen and .active under id #game
  • #game, .screen.active means: get me what has the id #game and anything with the classes .screen and .active (regardless of inside or outside #game)

Upvotes: 0

Related Questions