简体   繁体   中英

jQuery selector for elements in wrapper

When I use $('.color-wrap div') its select first div of both color-wrappers.

I need to select only first but they must be as a group so I can't use
$('.colorbox:first-child') or $('.colorbox-hard:first-child') .

I want to jQuery treat them as a group of 6 divs - its because, I want to choose one random div from group of six.

    <div class="wrapper">
        <div class="color-wrap">
            <div class="colorbox"></div>
            <div class="colorbox"></div>
            <div class="colorbox"></div>
        </div>
        <div class="color-wrap">
            <div class="colorbox-hard"></div>
            <div class="colorbox-hard"></div>
            <div class="colorbox-hard"></div>
        </div>
    </div>

How to select 1 div of div with class color-wrap only?

 var divs = $('.color-wrap div'); for(var i = 0 ; i < divs.length; i++){ console.log(divs[i]); // You can use like this. } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <div class="color-wrap"> <div class="colorbox"></div> <div class="colorbox"></div> <div class="colorbox"></div> </div> <div class="color-wrap"> <div class="colorbox-hard"></div> <div class="colorbox-hard"></div> <div class="colorbox-hard"></div> </div> </div> 
You can use also like this var divs = $('.color-wrap .colorbox, .color-wrap .colorbox-hard');

If I understand you correctly you could do something like this. refer to comments.

 $(document).ready(function() { // Collect all divs for both wrappers in variable var group = $('.color-wrap').find('div'); // Store the amount of items in the group variable var groupCount = group.length; // Store random number between 0 and the amount of items minus 1 var randomIndex = Math.floor(Math.random() * groupCount); // Use the random number as the key for the group variable to store one of the divs var randomElement = group[randomIndex]; console.log(randomElement); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <div class="color-wrap"> <div id="colorbox">One</div> <div id="colorbox">Two</div> <div id="colorbox">Three</div> </div> <div class="color-wrap"> <div id="colorbox-hard">Four</div> <div id="colorbox-hard">Five</div> <div id="colorbox-hard">Six</div> </div> </div> 

$('.color-wrap:first-child div:first-child')应该可以满足您的需求。

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