Select only the first children of a parent element

Asked

Viewed 548 times

1

I have the following appointment:

     <div class="step-content">
        <div id="step-1">
            <h1>step 1</h1>
            <h1>step 1</h1>
        </div>
        <div id="step-2">
            <h1>step 2</h1>
            <h1>step 2</h1>
        </div>
        <div id="step-3">
            <h1>step 3</h1>
            <h1>step 3</h1>
        </div>
     </div>

In this example I need to select only the elements #step-1, #step-2 and #step-3 to set display:none in each of them and not in their relative (.step-content).

Above I used div and id sequential, however, the selector should not depend on the type of the element (div, section, p and etc.) and neither his id or class

Which selector should I use to select all the first nodes that are children of .step-content independent of the HTML element?

1 answer

1


If you want to use only css, the trick is to use the >:

.step-content > * {
    display: none;
}

If you want to work with jQuery:

For this you can use the .children(). Example:

$('.step-content').children()

Return:

[<div id=​"step-1">​…​</div>​, <div id=​"step-2">​…​</div>​, <div id=​"step-3">​…​</div>​]

  • That’s it! I forgot about this css selector. With pure javascript I could also have used the property document.querySelector('.step-content').children // [<div id=​"step-1">​…​</div>​, <div id=​"step-2">​…​</div>​, <div id=​"step-3">​…​</div>​]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.