jQuery script to move an attribute of matched elements to their children
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="wid开发者_JAVA技巧th:200px">text</span></a>
I have no problem creating child span
but don't know how to move parent's width
styling.
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
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);
}
});
精彩评论