Jonathan Jonathan - 4 months ago 8
jQuery Question

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!

Answer

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

Comments