Anthony
Anthony

Reputation: 681

Javascript change class of an element

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.

Upvotes: 0

Views: 12729

Answers (4)

Jamie
Jamie

Reputation: 2255

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>

Upvotes: 4

womp
womp

Reputation: 116977

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";

Upvotes: 1

Deniz Dogan
Deniz Dogan

Reputation: 26227

Using JQuery:

$('ul li:nth-child(2)').attr('class', 'myclass');

Upvotes: -1

brettkelly
brettkelly

Reputation: 28205

using jQuery (naturally):

$(function(){
    $("li.something").removeClass("something").addClass("myclass");
});

Upvotes: 5

Related Questions