oxe
oxe

Reputation: 85

Im forcing to use getElementsByClassName()[] rather than getElementByClass()

I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......

When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....

I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(

Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.

This is exactly I want to achieve FIDDLE

Upvotes: 0

Views: 524

Answers (4)

Amadan
Amadan

Reputation: 198526

There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:

However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:

<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...

then you can:

$(document).ready(function(){
  $('.divbuttons').click(function() {
    var div = $(this).data("div");
    $('.divs.selected').removeClass('selected');
    $('#' + div).addClass('selected');
  });
});

Upvotes: 4

Balachandran
Balachandran

Reputation: 9637

try

$(document).ready(function () {

    $("button[class^=div]").click(function () {

        $(".divs.selected").removeClass("selected");

        $("#" + $(this).attr("class")).addClass("selected");

    });
});

DEMO

Upvotes: 1

Russell Bevan
Russell Bevan

Reputation: 334

This is an easy one. There is no document.getElementByClass

You have document.getElementById or document.getElementByClassName

Upvotes: 3

ray9209
ray9209

Reputation: 388

There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.

Upvotes: 2

Related Questions