Admin
Admin

Reputation: 13

How to Empty All Class Attributes from All HTML elements

I want to empty all html source code class attributes. For example, I have multiple elements values like div element, heading, and paragraph. Every HTML element content different class attributes just like below code.:

  <div class="card-body">
    <h5 class="card-title main-text-color ">My Mobile Phone is best
              </h5>
    <p class="">Lorem ipsum dolor sit amet, 
    </p>
    <p class="py-2">
        <a class=" main-color btn  text-light " href="#" class=" ">MORE DETAIL
                </a>
    </p>
</div>

Now I want to make it to be like the below code instead:

<div class="">
    <h5 class=" ">My Mobile Phone is best
              </h5>
    <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec imperdiet ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas
    </p>
    <p class="">
        <a class="  " href="#" class=" ">MORE DETAIL
                </a>
    </p>
</div>

How do I do this with Javascript in a browser?

Upvotes: 0

Views: 139

Answers (2)

EugenSunic
EugenSunic

Reputation: 13703

You can simply try this:

get All html elements, loop through them and set class attribute to empty string

const htmlElements = document.body.getElementsByTagName("*");

for (let i = 0; i < htmlElements.length; i++) {
  htmlElements[i].className=''
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370779

Use the query string [class] and use querySelectorAll to select all elements with a class attribute, and then set their className to the empty string:

document.querySelectorAll('[class]').forEach((elm) => {
  elm.className = '';
});
console.log(document.body.innerHTML);
<div class="card-body">
  <h5 class="card-title main-text-color ">My Mobile Phone is best
  </h5>
  <p class="">Lorem ipsum dolor sit amet,
  </p>
  <p class="py-2">
    <a class=" main-color btn  text-light " href="#" class=" ">MORE DETAIL
                </a>
  </p>
</div>

If you wanted to completely remove the class attributes, rather than setting them all to the empty string, instead use

elm.removeAttribute('class');

document.querySelectorAll('[class]').forEach((elm) => {
  elm.removeAttribute('class');
});
console.log(document.body.innerHTML);
<div class="card-body">
  <h5 class="card-title main-text-color ">My Mobile Phone is best
  </h5>
  <p class="">Lorem ipsum dolor sit amet,
  </p>
  <p class="py-2">
    <a class=" main-color btn  text-light " href="#" class=" ">MORE DETAIL
                </a>
  </p>
</div>

On older browsers that don't support NodeList.prototype.forEach, you can use for..of (if ES6 supported) or a plain for loop with manual iteration over indicies.

Upvotes: 1

Related Questions