0

I am trying to remove a class from a div and simultaneously add a class. It works fine if I dont have any data attributes attached to same div (I doubt its generally about data-attributes but guess its about the ones I have as they are used to produce effects).

Since removing/adding class doesnt work along with having data-attributes, I had the idea to remove data-attributes first, then remove/add class. The removal of the d. attr. works but then still I cannot remove/add a class. (To clarify why I dont just remove data.attr. from the html: I want add/remove a class for touch devices, where I dont need the data.attr., but need to keep them for other devices.)

I couldnt really find any solution..Any ideas?Thanks!

HTML:

<div id="welcomeFrame" class='frame2 frame' data-0='transform: scale(1.0,1.0);' data-150p='transform: scale(1.3, 1.3);opacity: 1;' data-200p='opacity: 0; transform: scale(6, 6);'>
</div>

JS:

var el = document.getElementById("welcomeFrame")
el.removeAttribute("data-0");
el.removeAttribute("data-150p");
el.removeAttribute("data-200p");
$("#welcomeFrame").removeClass("frame2").addClass("newFrame");
2
  • 1
    Adding and removing class strings from a node really has nothing at all to do with data attributes. Commented Mar 16, 2018 at 20:52
  • 1
    Since removing/adding class doesnt work along with having data-attributes, That's false. The two are not related. You have another issue. Commented Mar 16, 2018 at 20:54

1 Answer 1

1

There is nothing about data- attributes that conflicts with the adding and removing of classes.

Your code, however jumps back and forth between JQuery syntax and vanilla JavaScript, I would just pick one and stick with it. For something simple like this, I personally don't think JQuery is needed.

var el = document.getElementById("welcomeFrame");

el.removeAttribute("data-0");
el.removeAttribute("data-150p");
el.removeAttribute("data-200p");
el.classList.remove("frame2");
el.classList.add("newFrame");

// This shows that everything got removed/added as it should have:
console.log(el);
frame2 { background-color:green; border:1px solid red; } /* This is the default */
.newFrame { background-color:yellow; }                   /* And, this is applied later by code */
<div id="welcomeFrame" class='frame2 frame' 
     data-0='transform: scale(1.0,1.0);' 
     data-150p='transform: scale(1.3, 1.3);opacity: 1;' 
     data-200p='opacity: 0; transform: scale(6, 6);'>
     TEST
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.