Add class to class/all classes

Having probs adding a class to a class… Have had a google and tried a few diff ways but no luck.
I’m trying to change the layout views of panels by adding a class to a class…
html is like so…

<div class="item-c rowview">1</div>
<div class="item-c rowview">2</div>
<div class="item-c rowview">3</div>

With js ive tried…

var container  = document.getElementsByClassName("item-c")[0];
if (container.hasClass("rowview")){

no luck… and tried with

if ($(container).hasClass("rowview")){}

…amongst other tries!

Direction greatly appreciated here


If you are just adding a class to all elements called .item-c then just do this.


Or did you need something more specific?

Are you trying to detect if class is added to an element?
Then this is correct approach, but jQuery is required:


If you want to use only vanilla javascript, then use this function:

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;


if (hasClass(document.getElementsByClassName("item-c")[0], 'rowview')){ ... }

Yeah I’ve done both of what you both said above…except the vanilla…

FFS!!! forgot to include jquery ui :sob:


No worries. You won’t do that again :slight_smile:

JQuery is only ever required if you use JQuery. Anything that JQuery can do can also be done using ordinary JavaScript (since JQuery is written in JavaScript).

In this situation where container contains all of the nodes from the page that have the first class you simply need to loop over those to see which ones have the second class.

1 Like

That’s too obvious.
I know that, OP knows that. I have provided both solutions (with and without jQuery).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.