简体   繁体   中英

Remove CSS style rules from a single HTML element programatically

I want to add some HTML elements in my document that has no style at all. But I need to assure that these elements will not look differently regardless of project, webpage or anything else really. These elements will be inserted in the page by Javascript and will be SPAN.

My idea is to add SPANs to style snippets of text in the document. But some style might have been added to SPAN elements before and that will change the result I am expecting.

So let's assume I'm writing a Widget and any of you could be using it in your own webpages. This is why I can't do much to change the elements' style directly, like changing the stylesheets directly. The solution must be achieved by Javascript. JQuery is not wanted.

<head>
   <style>
     span{
       font-weight: bold;
       /*anything else goes below*/
     }
   </style>
</head>

<body>
   <span class='a_regular_span'>This text must be bold and anything else</span>
   <span>This text must have only the CSS rules I applied by Javascript, and must not inherit the rules for all SPANs in the page</span>
</body>

Any ideas?

So let's assume I'm writing a Widget and any of you could be using it in your own webpages. This is why I can't do much to change the elements' style directly

You could use a style element with scoped attribute. This way you can style only your elements, without affecting other parts of the page.

But be aware that old browsers don't support it.

And if you don't want page's styles to affect your elements, see How can I prevent CSS from affecting certain element?

If you really wish to separate the style of your elements from that of the other elements on the page, you could use a custom tag to do this.

For example, instead of using span, you could use customspan and style those elements any way you like.

<head>
   <style>
     span{
       font-weight: bold;
       /*anything else goes below*/
     }
   </style>
</head>

<body>
   <span class='a_regular_span'>This text must be bold and anything else</span>
   <customspan>This text must have only the CSS rules I applied by Javascript, and must not inherit the rules for all SPANs in the page</customspan>
</body>

can u try this?

 <style>
      span{
        font-weight: bold;
        /*anything else goes below*/
      }    .a_regular_span span{ font-weight: normal;
        /*anything else goes below*/
     }

 </style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM