Addition of elements

I am creating part of a webpage using .append() to add elements to another generated parent element. I want to style the added elements, but none of the styles provided to them using .css() are applied, perhaps due to the fact that these elements have not yet been added to the page?

Here is my code:

 var stickyHeader = $("<div></div>"); $(".stickyHeader").find("th").each(function() { var offset = $(this).offset().left; var objWidth = $(this).width(); stickyHeader.append("<span>" + $(this).html() + "</span>").css({width: objWidth, top: 0, left: offset, position: 'fixed'}); }); $("body").append("<div class=\"stickyHeader\">" + stickyHeader.html() + "</div>"); 

Do I need more .each() scroll span after they are added to body , or is there a more pleasant solution?

I forgot to mention that each span given a width from another element on the page, so this cannot be done only with CSS and classes.

+4
source share
5 answers

You apply css to the div container, not to the added elements, which I assume is what you need. Try:

 var span = $("<span>" + $(this).html() + "</span>"); .css({width: objWidth, top: 0, left: offset, position: 'fixed'}); stickyHeader.append(span); 
+4
source

.append forces you to redraw. This consumes resources and slows down your user interface. It’s best to create your HTML in an object or line and paste it into the DOM right away.

Let CSS do the hard work, preferably from an external stylesheet. String styles need to be parsed, which also slows down.

+3
source

A good, clean solution to adding styles to new elements is to make sure that they have the correct classes / identifiers and that you have a well-written CSS stylesheet.

0
source

If the class that you attach to the elements is already defined and styled in your css file, then the element will automatically accept these styles.

0
source

Another solution, use css file ^^, look at jsfiddle

0
source

All Articles