views:

21

answers:

2

I have a set of anchors like

<a class="lb" href="#">text</a>
<a class="lb" href="#" style="width:200px">text</a>
<a class="lb" href="#" style="color: reen; width:200px">text</a>

that needs to be transformed to the following:

<a class="lb" href="#"><span>text</span></a>
<a class="lb" href="#"><span style="width:200px">text</span></a>
<a class="lb" href="#" style="color:green"><span style="width:200px">text</span></a>

I have no problem creating child span but don't know how to move parent's width styling.

+3  A: 

For your example, the .wrapInner() and .css() functions should do it. Example:

$(document).ready(function(){
   var $anchors = $('a');
   $anchors.wrapInner('<span></span>');

   $anchors.children('span').each(function(i,v){
      $(this).css('width', $(this).parent().css('width'));
   });
});

Description: Wrap an HTML structure around the content of each element in the set of matched elements.

Note that in this example code, all anchros within your markup will be matched. You might want to be more specific by using classes or ids

jAndy
That's no problem for me. The real issue is moving anchor's width into the child span :(
UserControl
A: 

This should do it - sets an inner <span>, and copies over whatever css attributes are specified in to_be_moved:

$('.lb').each(function(){
    $(this).wrapInner('<span/>');
    var to_be_moved = ['width']; // array of css attributes to move
    for (var i=0;i<to_be_moved.length;i++){
        // get current value
        var currentValue = $(this).css(to_be_moved[i]);
        // set current value to nothing
        $(this).css(to_be_moved[i], '');
        // place the value into the child span
        $(this).children('span').css(to_be_moved[i], currentValue);
    }
});
artlung