I'm looking to break this span into two different ID's using jQuery:
<span id="foo">0.00 (0.00%)</span>
Outcome to look like:
<span id="foo1">0.00</span>
<span id="foo2">(0.00%)</span>
Any feedback appreciated.
I'm looking to break this span into two different ID's using jQuery:
<span id="foo">0.00 (0.00%)</span>
Outcome to look like:
<span id="foo1">0.00</span>
<span id="foo2">(0.00%)</span>
Any feedback appreciated.
Split the text contents into an array, create new nodes for each array element and then replace the current tag with the newly created elements:
$('#foo').replaceWith(function() {
var $this = $(this);
return $.map($this.text().split(' '), function(o, i) {
return $('<span>', {
id: $this.prop('id') + (i + 1),
text: o
}).get(0);
});
});
Granted, it might be a bit too generic for the actual question at hand :)
.text(). You could also have used .map instead of a for (...) { push } loop.var $foo = $('#foo');
var v = $foo.text().split(' ');
$foo.after($('<span id="foo2"></span>').text(v[1]));
$foo.after($('<span id="foo1"></span>').text(v[0]));
Demo ----> http://jsfiddle.net/ByFbK/3/
< in it?var orig = $('#foo').text().split(' '),str='';
$(orig).each(function (idx, elem) {
str += '<span id="foo' + (idx + 1) + '">' + elem + '</span>';
});
$('#foo').replaceWith(str);