Bojangles
Bojangles

Reputation: 101543

Styling appended elements

I'm building some 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 given to them using .css() are applied, possibly due to the fact these elements haven't been added to the page yet?

Here's 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 another .each() to loop through the spans once theyre added to body, or is there a nicer, cleaner solution?

I forgot to mention that each span is given a width from another element on the page, so this can't be done solely with CSS and classes.

Upvotes: 4

Views: 1751

Answers (5)

Awea
Awea

Reputation: 3183

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

Upvotes: 0

karim79
karim79

Reputation: 342775

You are applying the css to the container div and not the appended elements, which I guess is what you are after. Try:

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

Upvotes: 4

Jack
Jack

Reputation: 8941

If the class you are attaching to the elements is already defined and styled in your css file then the element will automatically take on those styles.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114437

.append forces a redraw. That consumes resources and slows down your UI. It's best to build up your HTML in an object or string and insert it into the DOM all at once.

Let CSS do the heavy-lifting, preferably from an external stylesheet. Inline styles must be parsed, which slows things down as well.

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179264

The nice, clean solution to adding styles to new elements is to make sure they have the correct classes/ids and that you've got a well-written CSS stylesheet.

Upvotes: 0

Related Questions