Jonathan
Jonathan

Reputation: 31

Javascript - Why does it only occur och first div and not on the second?

I don't know javascript really but have taken one witch works but it only works once on the first div on every page.

Look at this fiddle. [https://jsfiddle.net/Lr0g8snL/1/]

<div id="div4">jQuery Click to Toggle</div>
jQuery Click to Toggle

I you click the first div, it toggles the background on/off.

I've added the #div4 "jQuery Click to Toggle" twice and it only works on the first one.

How do i get it to work on all divs called #div4?

Thank you!

Upvotes: 0

Views: 44

Answers (1)

li0n_za
li0n_za

Reputation: 455

Each element should have a unique ID, use a class selector instead, or give them different IDs and select them then.

<div class="div4">jQuery Click to Toggle</div>

$(".div4").on("click", function() {
    $(this).toggleClass('back-red');
});

See fiddle

Upvotes: 2

Related Questions