4

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.

1
  • 4
    Have you tried anything yet? Please post your code. Commented Jun 17, 2013 at 16:13

4 Answers 4

3

This should work:

// obtain text and break it at the space
var t = $('#foo').text().split(' ');

// rename 'foo' and set its content
$('#foo').attr('id', 'foo1').text(t[0]);

// create new element and put it after foo
$('<span>', {id: 'foo2', text: t[1]}).insertAfter('#foo1');
Sign up to request clarification or add additional context in comments.

Comments

2

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 :)

2 Comments

granted, it does indeed more work to get the generic solution, but why (for example) use two different DOM methods to get the text instead of .text(). You could also have used .map instead of a for (...) { push } loop.
@Alnitak Reworked the answer with something less complicated and more jQuery'ish :)
0
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/

1 Comment

I always try never to concatenate strings and HTML to avoid string escaping issues. It's OK for the OP's input, but what it the text had an < in it?
0
var orig = $('#foo').text().split(' '),str='';
$(orig).each(function (idx, elem) {
    str += '<span id="foo' + (idx + 1) + '">' + elem + '</span>';
});
$('#foo').replaceWith(str);

jsFiddle example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.