Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove DOM element from variable with jquery

Tags:

html

jquery

dom

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>';
like image 593
petkopalko Avatar asked Aug 27 '12 09:08

petkopalko


3 Answers

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>'
like image 87
Roko C. Buljan Avatar answered Oct 01 '22 02:10

Roko C. Buljan


if you want to remove 'job2' from text

$(text).find("#job2").remove();
like image 44
Buzz Avatar answered Oct 01 '22 01:10

Buzz


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);​
like image 24
Vins Avatar answered Oct 01 '22 03:10

Vins