Take a look at this snippet:
const removeClassElement = document.getElementById('1');
removeClassElement.className = "";
// or classList = "" or classList = null or classList.remove(...removeClassElement.classList);
console.log(removeClassElement);
const removeAttributes = document.getElementById('2');
[...removeAttributes.attributes].forEach(attr => removeAttributes.removeAttribute(attr.name));
console.log(removeAttributes);
<p id="1" class="one two three">Lorem ipsum dolor sit amet</p>
<p id="2" style="color: green; font-weight: bold" title="title">Lorem ipsum dolor sit amet</p>
I am using typescript to adjust a templated html built file. In my TS file I have the following code:
let body = document.querySelector("body");
// Looking at using this to remove all attributes of certain types/names
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name))
The body variable is the BodyElement from the DOM and pulls it in fine. I need to parse all elements to remove the attributes called:
click.delegate="doSomething();"
show.bind="toggle();"
and the class:
aurelia-hide
It would be great to forEach through this once in TS to get rid of it all quickly.
I want to loop though the body (let body = …) that is the BodyElement and remove all the attributes and classes mentioned and then use body.innerHTML to build a new HTML file.
Is the [… something special in TS/JS? Just curious on that.
“…” is JS is either “spread” or “rest” operator/syntax. Spread syntax “expands” an array into its elements, while rest syntax collects multiple elements and “condenses” them into a single element. It’s really handy to do things like shallow copies of arrays/objects, when you need to pass a list of arguments to a function but you have an array, for object immutability and most important, it helps devs to deliver less (imperative!) code