最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to access inner span tag in jquery - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Nov 19, 2009 at 11:40 WonderingWondering 5,09622 gold badges73 silver badges90 bronze badges 1
  • Dup? stackoverflow./questions/1606629/… – moxn Commented Nov 19, 2009 at 11:48
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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

        $(".innerdiv span", this).css("border", "1px solid yellow");
    });
});
$ (.mydiv .inerdiv span:contains('inner span')).css("border", "1px solid yellow")
发布评论

评论列表(0)

  1. 暂无评论