Skip to content Skip to sidebar Skip to footer

Javascript Dynamically Adding And Removing Classes

I am working on a simple example, if a user clicks on element then all the elements above it should have a class and all elements below it should not have any class applied to them

Solution 1:

It might be wise to consider an alternative to using the onclick attribute due to separation of concerns. The following allows you to alter the HTML without having to consider JavaScript while you work.

https://jsfiddle.net/gseh0wxc/2/

vargetList = (selector) => [].slice.call(document.querySelectorAll(selector));

var paragraphs = getList("#divid p[id ^= 'p']");
paragraphs.forEach((paragraph, index) => {
  paragraph.addEventListener('click', (e) => {
    for (let i = 0; i < index; i++) {
      paragraphs[i].classList.remove('active');
    }
    for (let i = index; i < paragraphs.length; i++) {
      paragraphs[i].classList.add('active');
    }
  });
})

Solution 2:

Please try this code

functiontest(object) {
    var pid = object.id;
    var id = parseInt(pid.split("")[1]);
    console.log(id);
    for (var i = 1; i <= id; i++) {
        var element = document.getElementById("p"+i);
        element.classList.add("active");
    }
    console.log(id+1);
    for(var i = id+1; i <= 4; i++) {
        var element = document.getElementById("p"+i);
        element.classList.remove("active");
    }
}

Hope this helps.

Solution 3:

try this simple approach instead, don't need to extract id number and all, and with a single simple loop.

functiontest(option) {
//this will select all p tags id starts with "p" inside div having id "divid" and return a arrayvar targetPTags = document.querySelectorAll("div#divid p[id^=p]")
var idx, flag=false;
    //we are iterating over that array and taking each dom element in elfor(idx=0;idx<targetPTags.length;idx++) {
        var el = targetPTags[idx];
        if(flag) {
            //do operation you want for after elements in el
        } elseif(option===el) {
            flag=true; // we are making flag true when its the element that clicked and doing no operation//do the operation you want for the element, may be the same as below operation in else
        } else {
            //do operation you want for before element in el
        }
    }
}

Post a Comment for "Javascript Dynamically Adding And Removing Classes"