Ilja
Ilja

Reputation: 46527

store, remove and re apply class attribute with javascript

I need to temporary get rid of class attributes on html element to do sone parsing on it, however I need to store removed attribute somewhere and then somehow re-apply it back.

So far, I know I can pop and add attributes like this

div.removeAttribute("class")
div.setAttribute("class", "myClassname")

but that doesn't really help me out in terms of storing and re-applying it.

Upvotes: 3

Views: 317

Answers (3)

bugyt
bugyt

Reputation: 636

$("button").click(function(){
  attr = $("div").attr("class");
  $("div").removeAttr("class");
  $("div").attr("class", attr);
});

CodePen

Upvotes: 0

Sharon
Sharon

Reputation: 177

Actually it is not like

div.removeAttribute("class")
div.setAttribute("class", "myClassname")

It is like

div.removeAttr("class")
div.Attr("class", "myClassname")

I may be wrong either.. Jus give a try

Upvotes: 2

dfsq
dfsq

Reputation: 193311

You could store class attribute in some helper property which is not exposed as attribute. You can do it because HTMLElement's are normal objects so you can manipulate/set/read their properties, also create custom:

// set helper property
div.oldClass = div.className

// remove class attribute
div.removeAttribute('class')

// restore class attribute
div.setAttribute("class", div.oldClass)

Upvotes: 1

Related Questions