开发者

using the contents of <a> tag to set the li class with jquery

I have a simple drop-down menu:

<ul id="nav" >
<li><a href='/'>Parent One</a>
<ul>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
</ul>
</li>
<li><a href='/'>Parent Two</a>
<ul>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
</ul>
</li>

I need to assign a class to the < li > tag of the parent that is equal to the name of the parent in the < a > tag.

<ul id="nav" >
<li class="ParentOne"><a href='/'>ParentOne</a>
<ul>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
<li><a 开发者_高级运维href='/'>child</a></li>
</ul>
</li>
<li class="ParentTwo"><a href='/'>ParentTwo</a>
<ul>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
<li><a href='/'>child</a></li>
</ul>
</li>

I tried this bit of code:

    <script language="javascript" type="text/javascript">
 $('#navigation ul li a').each(function(index) {
 var link = $(this);
 $('li', link.parent()).addClass(link.text());
 });
 </script>

But that applies the class to the children's < li > tag and not the parent < li > - any help would be appreciated. Thanks!


$('#nav > li > a').each(function(){
    $(this).parent().addClass($(this).text().replace(/\s/, ''));
});


This should do it:

$(document).ready(function() {
    $('#nav > li > a').each(function(index) {
        $(this).parent().addClass($(this).text());
    });
});

That will also only act upon the top level li elements; in case you add classes to other deeper nested elements.


try this:

$(document).ready(function(){
    $('#nav>li>a').each(function(){
        $(this).parent().addClass($(this).text().replace(/\s/,''))
    });
});

:)

EDIT: Not thinking... omg... repaired :)

EDIT 2: Added white-space-trimming.

EDIT 3: Edited, added $document.ready, 100% working with white-space trimming ;)


This worked:

$("#nav li").each(function() { 
  $(this).addClass($(this).children("a").text());
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜