Search code examples
jqueryfunctionchaining

How to identify group elements enclosed by other element or tag?


I have question please refer the following code to understand the question. (I removed '<' and '>' character from the following html code because otherwise the html tags will not be visible so i have written only tag names)

<div>
    <div>
       <img />
       <img />
       <img />
       <img />
    </div>
</div>

I want to solve following task with the help of jQuery

  1. On document ready out of four img between the inner div only first img should be visible and rest of the three img should get hidden.
  2. Now on particular event like focus, click etc. the out of four img between the inner div the visible img get hide and the other one should get visible.

Some other questions:

  1. Is jQuery is able to identify only those elements enclosed by other tag?

  2. I also want to know how the control flows in jQuery? specially in chained function. for EX.

    1. $(selector).fun1(val,{fun2(){ }} in above example which function is get executed first and in what sequence.

    2. $(selecter).fun1().fun2().fun3() in above example which function is get executed first and in what sequence.

    3. In what sequence the functions in function chaining is get executed?

Waiting for your reply guys!


Solution

  • Try something like I did here.


    The first image (twitter) does not change, as per your requirements. The only images that are affected are the ones in the div that has the class sample

    HTML

    <img src="https://s3.amazonaws.com/twitter_production/a/1265328866/images/twitter_logo_header.png"/>
    
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    
    <div class="sample">
      <img src="http://sstatic.net/so/img/logo.png">
      <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif">
      <img src="http://cacm.acm.org/images/logo.ACM.gif">
      <img src="http://static03.linkedin.com/img/logos/logo_linkedin_88x22.png">
    </div>
    

    JavaScript

    $(function () {
        var textboxes = $("input:text"), //gets all the textboxes         
            images = $(".sample img");   //gets all the images
    
        images.not(":first").hide(); //hide all of them except the first one
        textboxes.each(function (i) {
            var j = i;
            $(this).focus(function () {
                images.hide().eq(j).show();
            });
        });
    });