JackNapier
JackNapier

Reputation: 448

Get only the first level children of type in javascript or jquery

I have the following html structure:

    <div class="tab-content">
        <div><p>First tab content</p></div>
        <div><p>Second tab content</p></div>
        <div><p>Third tab content</p><br />
            <div class="myvideos">
                <iframe src="http://www.youtube.com/embed/YWD2Z14w99Y"></iframe>
            </div>
        </div>
    </div>

and am using the following to get all the tab content divs:

$('.tab-content div').hide();

I want the jQuery function to only get the FIRST child elements inside the "tab-content" 's. CLARIFICATION - I want only the first Child divs one generation down, not their children

ie. Note that the THIRD tab content has a second child div that is being picked up which I want to ignore. I've also tried the following but they don't seem to work:

 $('.tab-content > div').hide();

 $('.tab-content div:first-of-type').hide();

Is there any way to only get the first children divs? This can be with jQuery or Vanilla JS.

Upvotes: 1

Views: 1992

Answers (4)

JackNapier
JackNapier

Reputation: 448

Turns out this did solve it in the end:

$(".tab-content > div").hide();

Upvotes: 0

Damian Orzusa
Damian Orzusa

Reputation: 1

$('.tab-content div:first-child').hide(); is the solution

Upvotes: 0

bricksphd
bricksphd

Reputation: 177

A Vanilla JS solution could look like this:

document.querySelector(".tab-content").children[0].style.visibility = "hidden"

Upvotes: 1

GMKHussain
GMKHussain

Reputation: 4691

Try this

jQuery(".tab-content > div").first().hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab-content">
        <div><p>First tab content</p></div>
        <div><p>Second tab content</p></div>
        <div><p>Third tab content</p><br />
            <div class="myvideos">
                <iframe src="http://www.youtube.com/embed/YWD2Z14w99Y"></iframe>
            </div>
        </div>
    </div>

Upvotes: 2

Related Questions