0

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.

cdub
  • 24,555
  • 57
  • 174
  • 303
  • Side Note: `document.body` is available. You don't have to look it up – Taplar Jan 15 '21 at 23:07
  • 1
    But where is `elem` defined? – Taplar Jan 15 '21 at 23:07
  • Does this answer your question? [Javascript: How to loop through ALL DOM elements on a page?](https://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page) and see: [Document.createNodeIterator()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator) – pilchard Jan 15 '21 at 23:08
  • 3
    If you want to remove an attribute from all elements I would suggest doing `document.querySelectorAll('[theAttribute]')` and then you'll get a list of only the elements that have that attribute. – Taplar Jan 15 '21 at 23:11
  • 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. – cdub Jan 15 '21 at 23:16

1 Answers1

0

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>
GBra 4.669
  • 1,512
  • 3
  • 11
  • 23
  • Is the [... something special in TS/JS? Just curious on that. – cdub Jan 15 '21 at 23:29
  • "..." 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 – GBra 4.669 Jan 15 '21 at 23:40