JQuery CSS select the first and last LI form of the UL List

Looking for some help with the jQuery CSS selector. I want to identify the first and last LI from the main UL list and change the CSS class. The first must be the class="grid_4 alpha" 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 can't use jquery.css functio correctly.

Help evaluate - I can add id to master ul if required

+3
source share
5 answers

Use :first-childand :last-childwith the child ( >) selector :

$("#master > :first-child").addClass("grid_4 alpha");
$("#master > :last-child").addClass("grid_4 omega");

Keep in mind that classes cannot have spaces in them. This markup:

<li class="grid_4 alpha">...

defines a list item that has two classes. If you want to select it, you can use:

$("li.grid_4.alpha")...

, grid_4, .

+10

:

http://api.jquery.com/first-selector/

http://api.jquery.com/last-selector/

:.

$("ul li:first").addClass("alpha");
$("ul li:last").addClass("omega");
+2
$('ul > li:first').addClass('alpha');
$('ul > li:last').addClass('omega');

, " "? , . , !

+1

:

$('ul li:first').addClass('alpha');
$('ul li:last').addClass('omage');

, :)

0

, , , :

id="linkcat-2"

.

:

<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>
0

Source: https://habr.com/ru/post/1732868/


All Articles