html - How do i toggle between classes of an element using javascript? -
this question has answer here:
- change element's class javascript 27 answers
i trying make script sets class label of checkbox when click once , when click again reverts first class.
this code have:
<label for="img1"> <img class="img1" src="images/testimg.jpg" onclick="javascript:test()" id="t1" /> </label> <input type="checkbox" class="chk " id="img1" name="img1" value="1" />
i want test function assign class img2 when called , when call again assign class img1.
javascript
function toggleclass(element, origin, target) { var newclass = element.classname.split(" "); (var = 0, < newclass.length; i++) { if (origin.localecompare(newclass[i]) == 0) { newclass[i] = target; }; }; element.classname = newclass.join(" "); }; // usage var img = document.getelementbyid("img1"); toggleclass(img, "img1 img2");
jquery
$("#img1").toggleclass("img1 img2");
more here.
Comments
Post a Comment