Wondering
Wondering

Reputation: 5076

how to access inner span tag in jquery

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?

Upvotes: 1

Views: 7059

Answers (3)

Dominic Rodger
Dominic Rodger

Reputation: 99761

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.

Upvotes: 5

Tinku
Tinku

Reputation: 1608

$ (.mydiv .inerdiv span:contains('inner span')).css("border", "1px solid yellow")

Upvotes: 0

hegemon
hegemon

Reputation: 6764

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

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

Upvotes: 0

Related Questions