Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "reset" styles for a given HTML element?

I am working on an embeddable javascript which inserts HTML elements onto unknown pages. I have no control of the stylesheets of the pages I'll be inserting HTML into. The problem is that the HTML I insert will mistakenly stylized by the page, and I want to prevent that.

What's the least verbose and/or resource intensive to go about ensuring the elements I insert are exactly as I'd like them to be? Is there an easy way to clear all styling for a given HTML element and children? In firebug, for instance, you can remove all styling. I feel like there must, and the very least should, be a native way to exempt certain HTML elements from stylesheet rules?

Example:

var myHTML = $("<div>my html in here</div>");
myHTML.resetAllStyles();   //<--- what would this function do?
myHTML.appendTo("body");

I really want to avoid explicitly stating the attributes I want for each element I insert...

PS: I have a lot of experience with JS and CSS, so you can assume that I'll understand pretty much anything you're going to tell me.

like image 548
Sambo Avatar asked Jun 10 '10 23:06

Sambo


2 Answers

I'm going to throw this out there as a possibility. How about custom tags for your bookmarklet? Requires a little more tinkering with a custom xml namespace because of IE, but may be workable for you.

jQuery doesn't seem to mind either.

http://jsfiddle.net/uvfAf/1/

jQuery:

$('#tester').animate({opacity: .3},1000);

HTML:

   // Not the main HTML tags. These are embedded in the body as the root
   //   of the bookmarklet. Scary? Perhaps.
<html xmlns:customtag>
    <style> 
        @media all {  
          customtag\:someElement { 
            width:100px; 
            height: 100px; 
            background: blue; 
            display: block; 
          } 
          customtag\:someOtherElement { 
            width: 50px; 
            height: 50px; 
            background: red; 
            display: block; 
          }
        }
    </style>
    <customtag:someElement id='tester'>test</customtag:someElement>
    <customtag:someOtherElement>test</customtag:someOtherElement>
</html>​

I used this page to figure out how to do custom tags in IE:

http://happyworm.com/blog/tag/custom-tags/

EDIT:

Looks like IE wants the xmlns to be defined in HTML tags, so I changed the container to <html>. Not sure of the ramifications overall, but seems to work.

I updated the example and the jsFiddle.

like image 174
user113716 Avatar answered Nov 01 '22 21:11

user113716


You cannot prevent an element inheriting CSS styles from parent nodes. All you can do is overwriting all styles that has been inherited.

like image 33
2ndkauboy Avatar answered Nov 01 '22 23:11

2ndkauboy