0

i am not able to select the element with class of a particular value for the below line

My HTML is

<ul class=nav>
   <li class="home">
       <a href="">HOME </a>
   </li>
   <li class="bye">
       <a href="">BYE </a>
   </li> 
</ul>

<script>
$("ul.nav li").click(function(e) {
   $('.home').addClass('.newhome').removeClass('.home');
    alert("done");
});
</script>

My CSS is

li.newhome {
    background: #678fef no-repeat;
     color:#fff;
    }

li.home{ 
 background: #666 no-repeat;

Here's a JSFiddle.

4
  • 3
    shouldn't you be using $(this) instead of $this? and what's []? Commented Jul 27, 2013 at 10:39
  • 1
    ...and use addClass instead. Commented Jul 27, 2013 at 10:42
  • That code doesn't really make much sense. What is $this. why are you storing the classes like that in the first place, why are you setting the attribute and not the property (className) with one of the many methods in jQuery etc. Explain as simple as possible what the intended functionality is, and maybe someone will suggest a better way to do it. Commented Jul 27, 2013 at 10:48
  • and your <a> tags are useless if you don't put anything in. Unless you're going to put an background image as a link. Commented Jul 27, 2013 at 10:58

3 Answers 3

3
var lastclickedclass=".home";
var updatedlastclass=".newhome";

$(lastclickedclass) is equivalent to $('.home')

for adding class you can use

$('.home').addClass('.newhome');

if you want to replace class

$('.home').addClass('.newhome').removeClass('.home');

if you want to refer in current code use

$(this).find('.home').addClass('.newhome');
Sign up to request clarification or add additional context in comments.

Comments

0

You can see the cleaned up fiddle at http://jsfiddle.net/ELbCx/15/.

What you just copy and pasted isn't even how jQuery works. If jQuery can't read it, it can't execute it.

Code is here:

HTML

<ul class=nav>
    <li class="home">HOME</li>
    <li class="bye">BYE</li> 
</ul>

jQuery

$("ul.nav li").click(function(e) {
    $(this).removeClass('home bye');
    $(this).addClass("newHome");
});

EDIT: Added removeClass to remove the existing classes.

2 Comments

yep i m tried expanding the code further plz see this when i click on bye the home1 class shud be reset to home but it doesn't jsfiddle.net/genius2k/ELbCx/18/...but it doesn't plz help
You've already accepted Tushar's answer, now all you need to do is figure it out to put it into code.
0

if you want to replace the existing class with a class by clicking on 'li' then it could be helpful..

$("ul.nav li").click(function(e) {
        $(this).removeClass($(this).attr('class')).addClass("newHome");
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.