Days
Hours
Minutes
Seconds

Super Black Friday Sale!

0
No products in the cart.
  • This topic is empty.
Viewing 15 posts - 1 through 15 (of 31 total)
  • Author
    Posts
  • #9679
    blanknathan-smith
    Participant

    How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

    #9681
    blankjon-galloway
    Participant

    This 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>
    
    #9680
    blankroenving
    Participant

    No 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";
    }
    
    #9700
    blankeric-bailey
    Participant

    The 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/','');
    
    #9702
    blankhiren-kansara
    Participant

    Change 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 Sub
    
    #9708
    blankpseudoninja
    Participant

    Using 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);
        }
    }
    
    #9704
    blankben-flynn
    Participant

    Just 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];
    
    #9706

    This is working for me:

    function setCSS(eleID) {
        var currTabElem = document.getElementById(eleID);
    
        currTabElem.setAttribute("class", "some_class_name");
        currTabElem.setAttribute("className", "some_class_name");
    }
    
    #9709
    blanktravis-j
    Participant

    Wow, surprised there are so many overkill answers here…

    <div class="firstClass" onclick="this.className='secondClass'">
    
    #9703
    blankalex-robinson
    Participant

    A 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, ' ') + "]");
    
    #9701
    blankshingokko
    Participant

    I 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.

    #9698
    blankalfred
    Participant

    Here’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")' >
    
    #9705
    blankmoka
    Participant

    As 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.

    #9696
    blanksalman-a
    Participant

    I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but 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.

    #9682
    blankuttamcafedeweb
    Participant

    Here 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.
Viewing 15 posts - 1 through 15 (of 31 total)
  • You must be logged in to reply to this topic.