开发者

jQuery: Modify appended object's CSS

开发者 https://www.devze.com 2023-01-26 02:38 出处:网络
$(\'#foo\').css({color:\'black\'}).append(\'<div>bar</div>\').css({color:\'red\'}); Given the above, the css() method is applied to foo, but how could you get it to apply to the div tha
$('#foo').css({color:'black'}).append('<div>bar</div>').css({color:'red'});

Given the above, the css() method is applied to foo, but how could you get it to apply to the div that wraps "bar"?

The only way I could think of to do this in the same execution line would be to create a jQuery div object inside of the append(function(){ ... }) and apply the styling there.


Note: I'm trying to avoid i开发者_StackOverflow社区nline styling (eg .append('<div style="color:red;">bar</div>')).


Update: I'm actually applying css to foo as well; The example has been updated to reflect this


You can flip the chain around so .css() runs on the appended element by using .appendTo() instead, like this:

$('<div>bar</div>').appendTo('#foo').css({color:'red'});
//or:
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
//or:
$('<div />', { text:'bar', css: {color:'red'} }).appendTo('#foo');


Try this:

$('<div>bar</div>').css({color:'red'}).appendTo('#foo');


$('#foo').append($('<div>bar</div>').css({color:'red'}));


or $something like

$('#foo').append($('<div />').text('bar').css({color:'red'}));


Easiest way is to use appendTo() rather than append():

$('<div>bar</div>').css({color:'red'}).appendTo('#foo');

You can find a working sample here: http://jsfiddle.net/YdzGZ/


what about:

$('#foo').append('<div>bar</div>').end().css({color:'red'});


How about you take a step back from the dynamic approach and create a rule or two in css?

#foo { color: black; }
#foo div,
#foo .orViaSomeClassName { color: red; }

No need to monkey about with injected inline styles that way.

And finally yet another approach to getting to the appended div:

$('#foo')
    .css('color', 'black') // css on #foo
    .append('<div>bar</div>') // appended to #foo
    .find('div')
        .css('color', 'red'); // css on divs inside #foo
0

精彩评论

暂无评论...
验证码 换一张
取 消