Jonathan Jonathan - 1 year ago 83
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. []

<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 Source

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() {

See fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download