gunacan
gunacan

Reputation: 21

How to change class name of an element that doesn't have an id?

<ul>
 <li class="bearname">Smokey</li>
 <li class="bearname">Teddy</li>
</ul>

how do I change those class names here? I tried;

document.querySelectorAll('li').className = "corgitype"

and

document.querySelectorAll('li').classList = "corgitype"

but nothing changes. corgitype is the new class name that I want to overwrite on bearname

Upvotes: 1

Views: 2088

Answers (4)

gavgrif
gavgrif

Reputation: 15509

You need to iterate over the results of the query which returns a node list - note that if you are setting more than one class on the li's then this will overwrite all classes. Incidentally - if its only stylnig you are trying to do - then you can get to the li's without a class at all in the css - ul > li {//css style rules} so classes may not even be needed.

EDIT - I have added a bit of extra fluff into this to allow toggling of the classes and styles -a bit more verbose - but easier to see the effect of the class name change.

function changeClass(value){
  var listItems = document.querySelectorAll('li');
  var index = parseInt(value);
  var type;
  index%2 == 0
   ? type = "corgitype"
   : type = "bearname"
    
  for(i=0;i<listItems.length;i++){
    listItems[i].classList= type;
   };
   document.getElementById('toggleButton').value = index+1;
}
.bearname {color:blue}
.corgitype {color: red}
<ul>
 <li class="bearname">Smokey</li>
 <li class="bearname">Teddy</li>
</ul>
<hr/>
<button type="button" onclick="changeClass(this.value)" value="0" id="toggleButton">Click to toggle classes</button>

Upvotes: 1

Junhee Shin
Junhee Shin

Reputation: 758

<html>
<head>
<style>
.classa {
color:red;
}
.classb {
color:blue;
}
</style>

<script>
function change() {
    var list = document.getElementsByTagName("li");
    for (var i=0; i<list.length; i++) {
    var el = list[i];
    el.classList.remove('classa') ;
    el.classList.add('classb') ;
    }
}
</script>
</head>

<body>
<li class="classa">aaa</li>
<li class="classa">bbb</li>
<button type="button" onclick="change();">change</button>
</body>

</html>

Upvotes: 0

brk
brk

Reputation: 50326

querySelectorAll returns a static collection. You need to iterate this collection and can use className which will replace the existing one

document.querySelectorAll('li').forEach(function(item) {
  item.className = 'corgitype';
})
.corgitype {
  color: green;
}
<ul>
  <li class="bearname">Smokey</li>
  <li class="bearname">Teddy</li>
</ul>

Upvotes: 2

A Franklin
A Franklin

Reputation: 121

You can use jQuery to accomplish this. You must include jQuery in your project or page to utilize its functionality. A tutorial for doing that exists here.

Once you have jQuery added, the easiest way to accomplish what you're after would be:

$('.bearname').addClass('corgitype').removeClass('bearname');

Upvotes: -1

Related Questions