rebellion
rebellion

Reputation: 6740

Removing HTML tag from string with jQuery

I have a form with several checkboxes and labels, most of the functionality is working correctly, but I'm having trouble getting the label value for the checkbox, while stripping out a span element inside the label:

<input type="checkbox" id="list-item-x" /> <label for="list-item-x"><span class="date">Oct 1</span> The checkbox label</label>

I want the label element, but without the span.date. How can I remove this? I've tried the following:

$('label').remove('span.date').text();

That didn't work, neither did the following:

$('label').find('span.date').text();

How can I only remove the span element, leaving the label text alone for later usage?

Edit: Here's the whole (messy) code:

$('input.list-item-checkbox').live('click', function(){
    var myself = $(this);
    var my_id = $(myself).attr('id').split('-', 3);
    my_id = parseInt(my_id[2]);
    var my_label = $(myself).parent().children('label').html();
    var parent = $(myself).parents('.list-item');
    if ($(this).is(':checked'))
    {
        $.ajax({
            type: 'POST',
            url: CI.base_url + 'ajax/unfinished_item/',
            data: 'list-item=' + my_id,
            dataType: 'json',
            success: function(result){
                if (result.status == 'ERROR')
                {
                    alert('Could not edit item');
                }
                else
                {
                    var html_string =
                        '<div class="list-item">' +
                        '    <input type="checkbox" class="list-item-checkbox" id="list-item-' + my_id + '" /> ' +
                        '    <label for="list-item-' + my_id + '">' + my_label + '</label>' +
                        '</div>';

                    $(myself).parents('.list-finished').siblings('.list-items').append(html_string);
                    $(myself).parents('.list-item-finished').remove();

                    // This is where I need to get the span element removed from the label
                }
            },
            error: function(){
                alert('No contact with server');
            }
        });
    }
});

Upvotes: 4

Views: 19419

Answers (2)

Alex Barrett
Alex Barrett

Reputation: 16455

$('span.date', my_label).remove();

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82483

var lbl = $("label");
var newLbl = $(lbl[0].outerHTML);
$("span", newLbl).remove();
alert(newLbl.text());

Upvotes: 5

Related Questions