开发者

jQuery select and apply style

开发者 https://www.devze.com 2023-02-11 14:43 出处:网络
I have a table with a lot of td cells. Each of t开发者_如何学JAVAhe cells might have a one or more divs inside. I need to take first inner div\'s inline style and move it to the parent td\'s style.

I have a table with a lot of td cells. Each of t开发者_如何学JAVAhe cells might have a one or more divs inside. I need to take first inner div's inline style and move it to the parent td's style.

How can this be done in jQuery?


This is very simple:

$('td div').each(function() {
  $(this).closest('td').attr('style', $(this).attr('style'));
});


$('td').find('div:first').each(function() {
   $(this).closest('td').attr('style', $(this).attr('style'));
})


To apply the first div style only:

$('td div:first-child').each(function(){
    $(this).parent('td').attr('style', $(this).attr('style'));
});


I'm guessing you want to get the computed style instead of the explicit style-argument of the div-element. There are few questions trying to find an answer in StackOverflow already

  1. jQuery CSS plugin that returns computed style of element to pseudo clone that element?
  2. How can I programmatically copy all of the style attributes from one DOM element to another

The solutions provide two ways to deal with this: either create a list of style properties you want to copy and iterate over them with parentTd.css(property, childDiv.css(property)) or use the computedStyle provided by the browser. Unfortunately the latter is not supported in Internet Explorer and needs a workaround.

0

精彩评论

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