- This topic is empty.
- AuthorPosts
-
October 12, 2008 at 8:06 am #9679
nathan-smithParticipantHow can I change the class of an HTML element in response to an
onclickor any other events using JavaScript?October 12, 2008 at 8:12 am #9681
jon-gallowayParticipantThis is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" /> <script> function test_byid() { $("#second").toggleClass("highlight"); } </script>October 12, 2008 at 8:16 am #9680
roenvingParticipantNo offense, but it’s unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.
The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you’ll only need to change a property or two, and that is easily implemented:
function highlight(elm){ elm.style.backgroundColor ="#345"; elm.style.color = "#fff"; }December 8, 2009 at 10:15 am #9700
eric-baileyParticipantThe line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');May 28, 2011 at 7:19 am #9702
hiren-kansaraParticipantChange an element’s CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'") lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'") lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'") lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'") End If End SubSeptember 20, 2011 at 3:26 am #9708
pseudoninjaParticipantUsing pure JavaScript code:
function hasClass(ele, cls) { return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(ele, cls) { if (!this.hasClass(ele, cls)) ele.className += " " + cls; } function removeClass(ele, cls) { if (hasClass(ele, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' '); } } function replaceClass(ele, oldClass, newClass){ if(hasClass(ele, oldClass)){ removeClass(ele, oldClass); addClass(ele, newClass); } return; } function toggleClass(ele, cls1, cls2){ if(hasClass(ele, cls1)){ replaceClass(ele, cls1, cls2); }else if(hasClass(ele, cls2)){ replaceClass(ele, cls2, cls1); }else{ addClass(ele, cls1); } }November 26, 2011 at 9:04 am #9704
ben-flynnParticipantJust to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args) goog.dom.classes.addRemove(element, classesToRemove, classesToAdd) goog.dom.classes.remove(element, var_args)One option for selecting the element is using goog.dom.query with a CSSÂ 3 selector:
var myElement = goog.dom.query("#MyElement")[0];December 8, 2011 at 9:36 am #9706
gopal-krishna-ranjanParticipantThis is working for me:
function setCSS(eleID) { var currTabElem = document.getElementById(eleID); currTabElem.setAttribute("class", "some_class_name"); currTabElem.setAttribute("className", "some_class_name"); }January 5, 2012 at 7:14 am #9709
travis-jParticipantWow, surprised there are so many overkill answers here…
<div class="firstClass" onclick="this.className='secondClass'">May 2, 2012 at 4:59 am #9703
alex-robinsonParticipantA couple of minor notes and tweaks on the previous regexes:
You’ll want to do it globally in case the class list has the class name more than once. And, you’ll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn’t care about case in class names.
var s = "testing one four one two"; var cls = "one"; var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig'); alert("[" + s.replace(rg, ' ') + "]"); var cls = "test"; var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig'); alert("[" + s.replace(rg, ' ') + "]"); var cls = "testing"; var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig'); alert("[" + s.replace(rg, ' ') + "]"); var cls = "tWo"; var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig'); alert("[" + s.replace(rg, ' ') + "]");May 5, 2012 at 2:46 am #9701
shingokkoParticipantI would use jQuery and write something like this:
jQuery(function($) { $("#some-element").click(function() { $(this).toggleClass("clicked"); }); });This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element’s class attribute if it’s not already part of it, and removes it if it’s there.
Yes, you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
October 17, 2012 at 12:21 pm #9698
alfredParticipantHere’s my version, fully working:
function addHTMLClass(item, classname) { var obj = item if (typeof item=="string") { obj = document.getElementById(item) } obj.className += " " + classname } function removeHTMLClass(item, classname) { var obj = item if (typeof item=="string") { obj = document.getElementById(item) } var classes = ""+obj.className while (classes.indexOf(classname)>-1) { classes = classes.replace (classname, "") } obj.className = classes }Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")' onmouseout='removeHTMLClass(this,"clsSelected")' >April 11, 2013 at 10:13 am #9705
mokaParticipantAs well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element; HTMLElement.prototype.addClass = function(string) { if (!(string instanceof Array)) { string = string.split(' '); } for(var i = 0, len = string.length; i < len; ++i) { if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) { this.className = this.className.trim() + ' ' + string[i]; } } } HTMLElement.prototype.removeClass = function(string) { if (!(string instanceof Array)) { string = string.split(' '); } for(var i = 0, len = string.length; i < len; ++i) { this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim(); } } HTMLElement.prototype.toggleClass = function(string) { if (string) { if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) { this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim(); } else { this.className = this.className.trim() + ' ' + string; } } } HTMLElement.prototype.hasClass = function(string) { return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className); }And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() { this.toggleClass('active'); }Here is demo.
January 18, 2014 at 9:28 am #9696
salman-aParticipantI use the following vanilla JavaScript functions in my code. They use regular expressions and
indexOfbut do not require quoting special characters in regular expressions.function addClass(el, cn) { var c0 = (" " + el.className + " ").replace(/\s+/g, " "), c1 = (" " + cn + " ").replace(/\s+/g, " "); if (c0.indexOf(c1) < 0) { el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, ""); } } function delClass(el, cn) { var c0 = (" " + el.className + " ").replace(/\s+/g, " "), c1 = (" " + cn + " ").replace(/\s+/g, " "); if (c0.indexOf(c1) >= 0) { el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, ""); } }You can also use element.classList in modern browsers.
April 6, 2014 at 6:10 am #9682
uttamcafedewebParticipantHere is a simple jQuery code to do that:
$(".class1").click(function(argument) { $(".parentclass").removeClass("classtoremove"); setTimeout(function (argument) { $(".parentclass").addClass("classtoadd"); }, 100); });Here,
- Class1 is a listener for an event.
- The parent class is the class which hosts the class you want to change
- Classtoremove is the old class you have.
- Class to add is the new class that you want to add.
- 100 is the timeout delay during which the class is changed.
- AuthorPosts
- You must be logged in to reply to this topic.