Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript ClassList in JS not working..

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #250596
    Pranab
    Participant

    i’m trying to hide the txt field if the Q word has the particular class..after clicking nothing happens..

    this is the jsfiddle link – https://jsfiddle.net/pranab/Lvfzgcc2/

    here is the js..

    var test = document.getElementById("icon");
    test.addEventListener("click",function(){
        var txt = document.getElementById("text");
        loadClass();
    })
    
    function loadClass(){
        if(txt.classList.contains("newClass")) txt.classList.remove("newClass");
        else txt.classList.add("newClass");
    }
    
    #250599
    Shikkediel
    Participant

    The var txt is limited to the scope of the event listener, so it is an unknown value inside the loadClass function. Try like this, raising the scope:

    var test = document.getElementById("icon"), txt;
    
    test.addEventListener("click", function() {
        txt =
    
    ...
    
    #250605
    Shikkediel
    Participant

    Or you could pass it as a parameter of course…

    var test = document.getElementById("icon");
    
    test.addEventListener("click", function() {
        var text = document.getElementById("text");
        loadClass(text);
    });
    
    function loadClass(txt) {
        if (txt.classList.contains("newClass")) txt.classList.remove("newClass");
        else txt.classList.add("newClass");
    }
    

    Or is that called an argument… I never know. :-/

    #250607
    Pranab
    Participant

    thanks @Shikkediel..in my case, the txt variable act like a local scope that’s why it’s not working..

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.