0

I have a table with a lot of td cells. Each of the 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?

johnlemon
  • 20,761
  • 42
  • 119
  • 178

4 Answers4

2

This is very simple:

$('td div').each(function() {
  $(this).closest('td').attr('style', $(this).attr('style'));
});
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
2
$('td').find('div:first').each(function() {
   $(this).closest('td').attr('style', $(this).attr('style'));
})
Vadim
  • 17,897
  • 4
  • 38
  • 62
1

To apply the first div style only:

$('td div:first-child').each(function(){
    $(this).parent('td').attr('style', $(this).attr('style'));
});
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
1

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.

Community
  • 1
  • 1
Aleksi Yrttiaho
  • 8,266
  • 29
  • 36
  • Started to browse before the clarification for inline style. I'll leave the comment so that others may be lead to the solutions to the more complicated scenario. – Aleksi Yrttiaho Feb 18 '11 at 06:12