简体   繁体   中英

How to select children elements but only one level

Here is my html code.

<div data-value="1">

    <div data-items="bind">
        <div data-item="Black" />
        <div data-item="Orange" />
    </div>

    <div data-types="bind">
        <div data-type="Books" />
        <div data-type="Mobiles" />
    </div>

    <button>button 1</button>
    <input type='text'/>

</div>

<div data-value="2">

    <div data-items="bind">
        <div data-item="Black" />
        <div data-item="Orange" />
    </div>

    <div data-types="bind">
        <div data-type="Gifts" />
        <div data-type="Cards" />
    </div>

    <button>button 1</button>

</div>

I have two parent divs that contains data-value "1" and "2".

first:

I want children of div that contains data-value="1" . The output should be 4 children 2 div, 1 button, 1 input

second:

I want children of div that contains data-value="2" . The output should be 3 children 2 div, 1 button

How is it possible using jQuery's.

Direct Descendant Selector

$("div[data-value='1'] > *");

Or children method:

$("div[data-value='1']").children();

Repeat as needed.

You can get the child element with .children()

$('div[data-value="1"]').children();

Source(s)

jQuery API - .children()

$("div[data-value='1']").children();

jsFiddle演示

Use the jQuery .children() function, combined with an attribute equals selector :

var $children1 = $('[data-value="1"]').children(); // children of element with data-value equal to 1

var $children2 = $('[data-value="2"]').children(); // children of element with data-value equal to 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM