I'm building a site that uses a JavaScript widget to embed a simple form into the page:
<script src="//example.com/formWidget.js?id=1234"></script>
This then injects the form HTML directly into the page for us to style to suit the site. However, the person who has made the form has included a lot of inline styling that's overriding the site's CSS. I don't want to make every CSS rule !important because that's usually a bad idea; and it's important to note that the inline styling is NOT done on a per-element basis (e.g. <span style="border: 1px solid red;">, which is solved in questions like this); but as a <style> block being injected into the page alongside the HTML:
<style>
.widget-form button {
border: 1px solid red;
float: left;
}
.widget-form input {
background: green;
}
</style>
The style block doesn't have an ID that I can selectively target, so how can I remove this injected inline style block? I'm fine using JS/jQuery to solve it, since that's how the widget is being added.
As long as the <style> block contains something uniquely identifiable, then it's relatively straightforward to remove. Using jQuery to loop through all the <style> blocks in the page, you can then check their content for the offending selector and remove the entire block:
$('style').each(function(index, elem) {
let styleBlock = $(this);
let content = styleBlock.text();
if (content.indexOf('.widget-form') > -1) {
// Found an inline style block - let's kill it!
styleBlock.remove();
}
});
You can also do this in a very similar way with plain JS:
var styles = document.querySelectorAll('style');
Array.prototype.forEach.call(styles, function(el, i) {
let content = el.textContent;
if (content.indexOf('.widget-form') > -1) {
// Found an inline style block - let's kill it!
el.remove();
// Or el.parentNode.removeChild(el); for maximum backwards compatibility
}
});
just put it on your css file
.widget-form button {
border: unset;
float: unset;
}
.widget-form input {
background: unset;
}
add !important if necessary
then try this
$( "<html>*/</html>" ).appendTo( "style:last-of-type" );
$( "<html>/*</html>" ).prependTo( "style:last-of-type" );
the selector changes according to your index file