javascript - Add class to selected div (div is not unique) -
i have different divs
have id="item"
. when select 1 of divs
, new class should added a
div has been selected. there way when ids not unique?
html:
<div class="something" id="item"> <a href="#" class="something">...</a> </div> <div class="something" id="item"> <a href="#" class="something">...</a> </div> <div class="something" id="item"> <a href="#" class="something">...</a> </div> <div class="something" id="item"> <a href="#" class="something">...</a> </div>
javascript (what have tried, not work):
// changes links on website $("body").delegate('#item', 'click', function() { $( "a" ).addclass( "active" ); });
edit: using delegate
function because create divs php, otherwise click event not registered.
don't ever have non-unique id, not valid. invalid ids aside, not working since using $("a")
targets links, rather specific one.
html:
<div class="something" id="item1"> <a href="#" class="something">...</a> </div> <div class="something" id="item2"> <a href="#" class="something">...</a> </div> <div class="something" id="item3"> <a href="#" class="something">...</a> </div> <div class="something" id="item4"> <a href="#" class="something">...</a> </div>
js
// doubt actual site uses in both cases, // made more explicit. $("body").on( 'div.something', 'click', function() { $('.active').removeclass( 'active' ); // use add active div $( ).addclass( "active" ); // use add active link $( ).find( 'a' ).addclass('active"); });
also note changed delegate
on
assuming using latest version of jquery - if not go delegate
Comments
Post a Comment