views:

111

answers:

4

I have ul list and I need to change the class of one of <li> tags with javascript:

<ul>
  <li>...</li>
  <li class="something"> <- need to change this class to "myclass" (javascript goes here)</li>
  <li>..</li>
</ul>

Thank you.

+5  A: 

using jQuery (naturally):

$(function(){
    $("li.something").removeClass("something").addClass("myclass");
});
inkedmn
you're too fast, I was nearly done :-)
Sander Rijken
Also note that this code changes all li elements with the "something" class
Sander Rijken
Also note that his example only contained one instance of the "something" class :)
inkedmn
So why even specify li?
Stefan Kendall
@Stefan how do you mean?
Sander Rijken
A: 

Using JQuery:

$('ul li:nth-child(2)').attr('class', 'myclass');
Deniz Dogan
this will remove any classes you might have wanted on the element. It's better to use $('...').addClass() and $('...').removeClass().
sakabako
Sorry, but he *did* say he wants the actual class to be `"myclass"`. Ridiculous to downvote this answer.
Deniz Dogan
A: 

Using regular javascript:

var listitems = document.getElementsByTagName("li");
for (int i = 0; i < listitems.length; i++)
{
   if (listitems[i].className == "something")
   {
      listitems[i].className = "new class name";
      break;
   }
}

If your <li> tag had an id attribute, it would be easier, you could just do

document.getElementById("liID").className = "newclassname";
womp
This will only work if something is the only class on the element, it won't work with class="something anotherthing".
sakabako
This will work with what the OP posted as an example. It's a minor detail to change it to work with other classnames. I purposely don't over-complicate example code.
womp
A: 

As there seems to be alot of jquery answers and it's not always possible to use jquery (for example if your customer/company won't let you use it arrgh!), here is a plain javascript example.

// Where 'e' is the element in question, I'd advise using document.getElementById
// Unless this isn't possible.

// to remove
if ( e.className.match(/something/) ) {
    e.className = e.className.replace("something", "")
}

// to add back in
if ( !e.className.match(/something/) ) {
    e.className += " something"
}

This will work with multiple classes, for example:

<li class="something another">...</li>
Jamie
Anybody got any ideas why this has been voted down? Is there a mistake somewhere I'm missing?
Jamie
They are just jQuery evangelists down voting whoever speaks against their holy grail.
drlouie - louierd
If I didn't know hwo to write real JavaScript from scratch, as most jQuery evangelists tend to be incapable of, I would also down vote your answer, heh!
drlouie - louierd