How to protect inline div style that will not be overridden by website style

I have a div with my own style. I have embedded this div in another website.

<div id="scoped-div">
  <style>
    label {
      color: green;
    }
  </style>

  <label> Scoped div </label>
</div>

But I am facing a problem, my div style is overridden by the style of the website. I do not want to use iframe. Except for use, is iframethere any other way to protect my div style with external style changes?

+1
source share
2 answers

Your request exactly matches the Shadow DOM :

  • attach the shadow DOM to the element you want to protect (here:) #scope-div,
  • HTML-, DOM DOW,
  • <template>, ().

!

var div = document.querySelector( "#scoped-div" )
var template = document.querySelector( "template" )

var sh
if ( 'attachShadow' in div )
  sh = div.attachShadow( { mode: "closed" } )  //Shadow DOM v1
else
  sh = div.createShadowRoot()                 //Shadow DOM v0 fallback

sh.appendChild( template.content.cloneNode( true ) )
<template>
  <style>
    label {
      color: green;
    }
  </style>

  <label> Scoped div </label>
</template>

<div id="scoped-div">
</div>
Hide result
+3

. :

  • (, ).
  • !important ( )
+2

All Articles