petkopalko
petkopalko

Reputation: 610

Remove DOM element from variable with jquery

Please help me solve this:

I have got this:

var text='<li id="job1">Job 1</li>'+
         '<li id="job2">Job 2</li>'+
         '<li id="job3">Job 3</li>';

and I want to remove one element, something like this:

$("#job2",$(text)).remove();

this doesnt work. Is there a way how to do it? thanks.

EDIT: And I want to save result back to text:

 text='<li id="job1">Job 1</li><li id="job3">Job 3</li>';

Upvotes: 7

Views: 7546

Answers (3)

Vinayak Phal
Vinayak Phal

Reputation: 8919

Try like this...

*Update FIDDLE My first version of code $(text).find("#job2").remove(); did't worked in jsfiddle, but when I've added <ul></ul> to the code its worked like charm. I've no idea why did't worked with first instance without ul And I do not see any occasion where li will come without ul So please try like this.

var text='<ul><li id="job1">Job 1</li>'+
         '<li id="job2">Job 2</li>'+
         '<li id="job3">Job 3</li></ul>';

$text = $(text);
// console.log($text);
$text.find("li#job2").remove();
// console.log($text.find("li#job2"));
$('div').append($text);​

Upvotes: 2

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

your var text is just a variable that's holding a string

<li id="job1">Job 1</li><li id="job2">Job 2</li><li id="job3">Job 3</li>

And string is not an object so you cannot use .remove()


But once you do for eg:

$('#someElement').append(text);

than you can simply do:

$('#job2').remove();

and retrieve your new string using:

text = $('#someElement').html(); // '<li id="job1">Job 1</li><li id="job3">Job 3</li>'

Upvotes: 3

Buzz
Buzz

Reputation: 6330

if you want to remove 'job2' from text

$(text).find("#job2").remove();

Upvotes: 2

Related Questions