Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - get all divs inside a div with class ".container"

Tags:

jquery

dom

Scenario:

I got a menu containing links:

Main Menu Item
--------------
Sub: Show Grid > SubSub: <a>Show #first</a>
                         <a>Show #second</a>
                         <a>Show #third</a>

Now i need to find all divs with an css #ID who are first level DOM elements inside the .container div. These elements should get appended to "Sub: Show Grid" and add a class via a click on it.

<!-- The mark up -->
<div class="container">
    <div id="first">1st</div>
    <div id="second">2nd</div>
    <div id="third">3rd</div>
</div>

Question:

  • How would i find the first level div with an (undefined/not known) #ID with jQuery?
  • How can i interact with the result in php - will I get an array as result to build the SubSub menu out of it?

Thanks in advance!


Edit #1

To make it more clear what I'm trying to do - In pseudo code:

$divs_received_from_jquery_fn = 'how do I get the divs (IDs?) as array(?) and interact with them in the following code?';
foreach ( $divs_received_from_jquery_fn as $div )
{
    add_menu_item( array( 
         'parent' => 'Sub: Show Grid'
        ,'name'   => 'Show #'.$div
        ,'href'   => ''
        ,'meta'   => array( 
                        'onclick' => 'jQuery(".container #".$div).toggleClass("showgrid");'
         ) 
    ) );
}

Edit #2

The "real world" example. The output is an onclick event for an a-link. My problem is that i want to call the function foreach for every div[id] below the .container div and simply don't know how to interact properly with javascript & php.

?>
<script type="text/javascript">
    jQuery(".container > div[id]").each(function(){
        var context = $(this);
        <?php 
        // SHOWGRID - parts
        // @since v0.3
        $wp_admin_bar->add_menu( // trigger the function via the global $wp_admin_bar var that calls the class
            array(
                 'parent'   => 'showgrid' // parent menu item
                ,'id'       => 'showgrid - ' + this.id // menu item ID
                ,'title'    => sprintf( // menu item label
                     __( '%1$s show grid parts %2$s%3$s', OXO_TEXTDOMAIN )
                    ,'<span style="background: none;">'
                    ,'<span class="showgridparts-on hide">&#x2714;</span>'
                    ,'<span class="showgridparts-off">&times;</span>' 
                 )
                ,'href'     => '' // stays empty to not trigger anything
                ,'meta'     => array( // HERE GOES THE ACTUAL jQuery FUNCTION
                    'onclick'   => 'jQuery("#" + this.id).toggleClass("showgrid"); jQuery(".showgridparts-on").toggleClass("hide"); jQuery(".showgridparts-off").toggleClass("hide"); return false;'
                 )
            ) 
        );
        ?>
    });
</script>
<?php
like image 439
kaiser Avatar asked May 12 '11 12:05

kaiser


3 Answers

Known ID

$(".container > #first");

or

$(".container").children("#first");

or since IDs should be unique within a single document:

$("#first");

The last one is of course the fastest.

Unknown ID

Since you're saying that you don't know their ID top couple of the upper selectors (where #first is written), can be changed to:

$(".container > div");
$(".container").children("div");

The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.

If you also need to filter out only those child DIV elements that define ID attribute you'd write selectors down this way:

$(".container > div[id]");
$(".container").children("div[id]");

Attach click handler

Add the following code to attach click handler to any of your preferred selector:

// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
    // if you need element's ID
    var divID = this.id;
    cache your element if you intend to use it multiple times
    var clickedDiv = $(this);
    // add CSS class to it
    clickedDiv.addClass("add-some-class");
    // do other stuff that needs to be done
});

CSS3 Selectors specification

I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.

After your edited question

I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:

$(".container > div[id]").each(function(){
    var context = $(this);
    // get menu parent element: Sub: Show Grid
    // maybe I'm not appending to the correct element here but you should know
    context.appendTo(context.parent().parent());
    context.text("Show #" + this.id);
    context.attr("href", "");
    context.click(function(evt){
        evt.preventDefault();
        $(this).toggleClass("showgrid");
    })
});

the last thee context usages could be combined into a single chained one:

context.text(...).attr(...).click(...);

Regarding DOM elements

You can always get the underlaying DOM element from the jQuery result set.

$(...).get(0)
// or
$(...)[0]

will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.

But when I used .each() function and provided an anonymous function that will be called on each element in the set, this keyword actually refers to the DOM element.

$(...).each(function(){
    var DOMelement = this;
    var jQueryElement = $(this);
    ...
});

I hope this clears some things for your.

like image 51
Robert Koritnik Avatar answered Nov 11 '22 11:11

Robert Koritnik


To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")
like image 26
James Wiseman Avatar answered Nov 11 '22 11:11

James Wiseman


To set the class when clicking on a div immediately within the .container element, you could use:

<script>
$('.container>div').click(function () {
        $(this).addClass('whatever')
    });
</script>
like image 1
Digbyswift Avatar answered Nov 11 '22 11:11

Digbyswift