Visualization
Visualization

Reputation: 47

Jquery: Select all elements below - do multiple function to each element

I want to select each of element below and apply multiple jquery commands to it, any command.

HTML:

<body>
    <div class="option"></div>
    <div class="option"></div>
    <div class="option"></div>
    <div class="last"></div> <!-- SELECT FROM HERE -->
    <div class="option"></div>
    <div class="option">
    <img src="a.jpg"/>
    <table>
       <td><tr>1</tr></td>
       <td><tr>2</tr></td>
    </table>
    </div>
    <div class="option"></div>
</body>

jQuery:

$(".last").nextAll().each(function () {

       $(this).css('background-color','red');
       $(this).addClass('below');
       var thisobj = $(this);
       //Example ->
       $(this).load(function() {
           $(thisobj).addClass('loaded');
       });
       $(this).error(function(){
           $(thisobj).addClass('error');
       });
       //more code etc...

});

To make html look like this with jQuery: select everything below class and apply functions. Count if all divs have loaded.

<body>
    <div class="option"></div>
    <div class="option"></div>
    <div class="option"></div>
    <div class="last"></div>
    <div class="option loaded" style="background-color:red;"></div>
    <div class="option error" style="background-color:red;">
         <img class="loaded" style="background-color:red;" src="a.jpg"/>
         <table class="loaded" style="background-color:red;">
               <tr class="error" style="background-color:red;">
                  <td class="loaded" style="background-color:red;">abc</td>
               </tr>
               <tr class="loaded" style="background-color:red;">
                  <td class="loaded" style="background-color:red;">abc</td>
               </tr>
         </table>
    </div>
    <div class="loaded" class="option" style="background-color:red;"></div>
</body>

Upvotes: 0

Views: 1795

Answers (1)

Birdman
Birdman

Reputation: 724

Here you go. This will let you traverse the DOM tree. I'm only applying the red style to show it works, but you can modify it accordingly

function style_children(parent) {
    parent.css('background-color', 'red');
    parent.children().each(function() {
        style_children($(this));
    });
}

$(".last").nextAll().each(function() {
    style_children($(this));
});

And correct me if I'm wrong, but if this placed in $(document).ready() function, like it should be, your load and error functions won't fire b/c they have already fired before your entire document was ready. The load and error functions will only work if you adding content dynamically after the doc.ready has been fired.

Upvotes: 7

Related Questions