Reputation: 573
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.
Upvotes: 0
Views: 4084
Reputation: 9953
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>
Upvotes: 1
Reputation: 22574
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);
Upvotes: 2