Al-76
Al-76

Reputation: 1878

How to target a specific tag and add a class in JQuery

I am trying to tell JQuery to find the section with the class of 'listings', then find the class 'result'. Then add a new class of 'last' to this very last li only.

<section class="listings">
   <div class="ignore-this-div">
       <div class="ignore-this-div-as-well">
           <ul>
               <li class="result"></li>
               <li class="result"></li>
           </ul>
       </div>
   </div>
</section>

$(document).ready(function()
    $('listings .result').last.addClass('last')
});

Upvotes: 0

Views: 564

Answers (4)

Miodrag
Miodrag

Reputation: 97

You are missing bracket after $(document).ready(function(), last is a method and should look like last(), you'll also have to put semicolon after $('listings .result').last().addClass('last')

Your jQuery should look like:

$(document).ready(function(){
    $('.listings ul li').last().addClass('last');
});

Upvotes: 0

Wesley Smith
Wesley Smith

Reputation: 19571

You have a few issues with your syntax, this would work:

$(document).ready(function(){
    $('.listings ul li').last().addClass('last');
});
.last{
background-color:#ccc;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="listings">
   <div class="ignore-this-div">
       <div class="ignore-this-div-as-well">
           <ul>
               <li class="result">first</li>
               <li class="result">last</li>
           </ul>
       </div>
   </div>
</section>

Upvotes: 0

cssyphus
cssyphus

Reputation: 40106

Also, could do it like this:

$('.listings .result:last-child').addClass('last')

https://jsfiddle.net/1e0ysd1d/

Upvotes: 0

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

You have invalid last function, should be .last() and the listings classname selector should have . like following :

$('.listings .result').last().addClass('last');

or you can use :last :

$('.listings .result:last').addClass('last');

Upvotes: 3

Related Questions