i have this piece of code where i wanna check if a css class is present,if so then want to remove that specific class.
var el = document.querySelector('.main-content');
const promo = 'projectPromoActivateMobile';
const transaction = 'projectTransactionActivate';
const newsletter = 'projectNewsletterActivate';
const landingPage = 'projectLandingPageActivate ';
const classLists = [promo,transaction,newsletter,landingPage]
let check = el.classList.contains(promo || transaction ||newsletter || landingPage);
console.log(check);
this does the work and check but can not seem to get the name of the class,which needs to be removed.
how would you check if that specific css class is present in the element?
CodePudding user response:
promo || transaction || newsletter || landingPage
will resolve to promo
, since all values are strings of non-zero length (therefore truthy). All following values will be ignored.
Therefore, this code :
let check = el.classList.contains(promo || transaction ||newsletter || landingPage);
is exactly the same as this :
let check = el.classList.contains(promo);
Instead, you want to use something like this:
const classLists = ["promo","transaction","newsletter","landingPage"];
let check = el.classList.some(class => classLists.includes(class));
CodePudding user response:
To remove a class, use element.classList.toggle(className, false)
, second parameter false
for removal only.
var el = document.querySelector('.main-content');
const promo = 'projectPromoActivateMobile';
const transaction = 'projectTransactionActivate';
const newsletter = 'projectNewsletterActivate';
const landingPage = 'projectLandingPageActivate';
const classLists = [promo,transaction,newsletter,landingPage]
console.log(el.classList.contains(promo));
console.log(el.classList.contains(transaction));
classLists.forEach(clazz => el.classList.toggle(clazz, false));
console.log(el.classList.contains(promo));
<div class="main-content projectPromoActivateMobile"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>