Home > database >  How to save css style of element after refreshing the page in JavaScript?
How to save css style of element after refreshing the page in JavaScript?

Time:07-10

For example, after clicking on Hide button some items disappear

function hideItem() {
            targList = document.getElementsByClassName("completed");
            document.getElementsByClassName("completed")
            if (targList) {
                for (var x = 0; x < targList.length; x  ) {
                    targList[x].setAttribute('style', 'display: none !important');
                }
            }
            localStorage.setItem("autosave", targList);
        }

But after refreshing the page style of items do not save. How to preserve this style of element after reloading web page?

CodePudding user response:

You can't store DOM into localStorage. You'd have to save identifying code for each element. For example, id.

Then do the opposite after loading the page.

function hideItem() {
  var targList = document.getElementsByClassName("completed");
  var hidden_ids = []
  for (var x = 0; x < targList.length; x  ) {
    targList[x].setAttribute('style', 'display: none !important');
    hidden_ids.push(targList[x].id)
  }
  localStorage.setItem("autosave", JSON.stringify(hidden_ids));
}

function loadItem() {
  var hidden_ids = Json.parse(localStorage.getItem("autosave") || '[]');
  for (var x = 0; x < hidden_ids.length; x  ) {
    document.getElementById(hidden_ids[x]).setAttribute('style', 'display: none !important');
  }
}
hideItem();
<div id="elem1" >hello</div>
<div id="elem2" >hello</div>

  • Related