Jquery selector: jquery function which alters the style of the `<li>` containing the 'quit' link
Given following html code:
<ul>
<li>
<a href="somelink">
<span class='someIconCss'></span>
<span>home</span>
</a>
</li>
[possibly some more <li></li>]
<li>
开发者_如何学运维<a href="somelink">
<span class='someIconCss'></span>
<span>quit</span>
</a>
</li>
[possibly some more <li></li>]
</ul>
I would like to have a jquery function which alters the style of the <li>
containing the 'quit' link.
For now, I have the following:
jQuery("li > a > span > span:contains('quit')").parent().parent().parent().attr("style", "float:right");
but I'm pretty sure there is a better way.
Problem is that jQuery("li > a > span > span:contains('quit')")
returns the span element in stead of the <li>
Most readable answer wins...
You can use .has()
$('li').has('span:contains("quit")')
or go the other way and use .closest()
:
$('span:contains("quit")').closest('li')
// maybe with `$('ul span:contains("quit")')` if you have another span with
// `quit` somewhere in the page. Even better: Give your menu an id!
More understandable might also be a:contains("quit")
, as it is clearer that you mean the quit link...
If you know the word 'quit' can't appear anywhere else:
jQuery('li:contains("quit")')
since contains
checks all descendants, not just children.
Working demo at http://jsfiddle.net/alnitak/r8yBb/
You need the :has()
selector:
jQuery('li:has(span:contains("quit"))').css('float', 'right');
Note that I've also used the css
method for setting the style.
Based on your original code:
jQuery("li > a > span > span:contains('quit')").closest("li")
will give you the containing <li>
element.
Check this out:
$('li:contains("quit")').css("float", "right");
精彩评论