looking for some help please with the JQuery CSS selector. I want to identify the first and last LI from the main UL list and alter the CSS class. The 开发者_JAVA百科first should be
class="grid_4 alpha"
and the last
class="grid_4 omega"
<ul>
<li id="linkcat-2" class="grid_4 this should be alpha"><h4 class="widgettitle">Blogroll</h4>
<ul class='xoxo blogroll'>
<li><a href="http://wordpress.com/">WordPress.com</a></li>
<li><a href="http://wordpress.org/">WordPress.org</a></li>
</ul>
</li>
<li id="linkcat-2" class="grid_4"><h4 class="widgettitle">Blogroll</h4>
<ul class='xoxo blogroll'>
<li><a href="http://wordpress.com/">WordPress.com</a></li>
<li><a href="http://wordpress.org/">WordPress.org</a></li>
</ul>
</li>
<li id="linkcat-2" class="grid_4"><h4 class="widgettitle">Blogroll</h4>
<ul class='xoxo blogroll'>
<li><a href="http://wordpress.com/">WordPress.com</a></li>
<li><a href="http://wordpress.org/">WordPress.org</a></li>
</ul>
</li>
<li id="linkcat-2" class="grid_4 this should be omega"><h4 class="widgettitle">Blogroll</h4>
<ul class='xoxo blogroll'>
<li><a href="http://wordpress.com/">WordPress.com</a></li>
<li><a href="http://wordpress.org/">WordPress.org</a></li>
</ul>
</li>
</ul>
I just cannot get the right JQuery.css functio to work.
Help much appreciated - I can add an id to the master ul if requyired
Use :first-child
and :last-child
with the child (>
) selector:
$("#master > :first-child").addClass("grid_4 alpha");
$("#master > :last-child").addClass("grid_4 omega");
Bear in mind that classes can't have spaces in them. This markup:
<li class="grid_4 alpha">...
defines a list element that has two classes. If you want to select it you can use:
$("li.grid_4.alpha")...
meaning select all the list elements that have both the grid_4 and alpha classes.
You should use the following selectors:
http://api.jquery.com/first-selector/
http://api.jquery.com/last-selector/
e.g.:
$("ul li:first").addClass("alpha");
$("ul li:last").addClass("omega");
$('ul > li:first').addClass('alpha');
$('ul > li:last').addClass('omega');
Hey remember the end of Beneath The Planet Of The Apes? That was pretty cool, with the big bomb and everything. Oops I hope I didn't give it away for anybody!
How about this:
$('ul li:first').addClass('alpha');
$('ul li:last').addClass('omage');
Hope this helps :)
One thing that may cause you a problem in your example is that you have assigned the same id to many items:
id="linkcat-2"
The id is supposed to be unique.
However, this is how you select first and last:
<ul id="main">
<li>One</li>
<li>Two
<ul>
<li>Two A</li>
<li>Two B</li>
</ul>
</li>
<li>Three</li>
<li>Four
<ul>
<li>Two A</li>
<li>Two B</li>
</ul>
</li>
</ul>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
alert($("#main > :first-child").text());
alert($("#main > :last-child").text());
</script>
精彩评论