0

I'm getting data from Wordpress, which contains HTML with inline styles. Before I insert this HTML into my React website, I would like to remove all inline styles. For example, I get something like:

<div style='height: 500px'>
<img  style='height: 300px; width: 250px'/>
... more elements with inline styles
</div>

I'm looking for a clean way of doing this because I've tried using other solutions on SO and they use Jquery and other JS methods which would not work since I'm using React to build my website.

0

2 Answers 2

2

You call select all the html tags and using document.querySelectorAll('*') and iterate through each one of them and using removeAttribute, removes style attribute.

const htmlString = `<div style='height: 500px'>
<img  style='height: 300px; width: 250px'/>
<p> text</p>
<div style="color: red">Red text</div>
... more elements with inline styles
</div>`;
const htmlNode = document.createElement('div');
htmlNode.innerHTML = htmlString;
htmlNode.querySelectorAll('*').forEach(function(node) {
    node.removeAttribute('style');
});
console.log(htmlNode.innerHTML);

Sign up to request clarification or add additional context in comments.

Comments

1

You can find all tag in your body then use removeAttribute to remove style attribute.

function remove(){

   var allBodyTag = document.body.getElementsByTagName("*");

   for (var i = 0; i < allBodyTag.length; i++) {
       allBodyTag[i].removeAttribute("style");
   }
}
<button onClick="remove()">Remove </button>
<div style='height: 500px'>
This is text
<img  style='height: 50px; width: 250px'/>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.