views:

220

answers:

3

Hi All, I have a HTML structure:

            <div class="mydiv">xx
               <span>test1</span>
               <span>test2</span>
              <div class="inerdiv">
                 <span>inner span</span>
               </div>
               </div>
             <span>test3</span>

Now I want to apply styling to the span which contains "inner span" .

$(function() {
        $(".mydiv").click(function() {

            $(".mydiv").next().find("span").css("border", "1px solid yellow");//not working
        });
    });

what should be the proper code?

+2  A: 

Replace:

$(".mydiv").next().find("span").css("border", "1px solid yellow");

With:

$(".mydiv .innerdiv span").css("border", "1px solid yellow");

I don't think next() does what you think it does.

next() returns the immediate next sibling of all previous matched elements.

Given the markup:

<div class="hello">foo1</div><span>bar1</span>
<div class="goodbye">foo2</div><span>bar2</span>
<div class="hello">foo3</div><span>bar3</span>

The following will return the span elements containing bar1 and bar3:

$("div.hello").next()

Therefore, there's no way to get the <div class="innerdiv"> from the outer div using next(), since they are not siblings.

Dominic Rodger
agreed. but is there any way to do with next() and find()?No special reason, just want to know.
Wondering
@Wondering - edited in an explanation.
Dominic Rodger
Thanks, for the example.
Wondering
A: 
$(function() {
    $(".mydiv").click(function() {

        $(".innerdiv span", this).css("border", "1px solid yellow");
    });
});
hegemon
A: 
$ (.mydiv .inerdiv span:contains('inner span')).css("border", "1px solid yellow")
Tinku