Job 1'+ '
  • Remove DOM element from variable using jquery

    Please help me solve this problem:

    I have it:

    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 does not work. Is there any way how to do this? thanks.

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

      text='<li id="job1">Job 1</li><li id="job3">Job 3</li>'; 
    +8
    jquery dom html
    source share
    3 answers

    your var text is just a variable containing a string

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

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


    But as soon as you do, for example:

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

    than you can just:

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

    and get a new line using:

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

    Try it...

    * Update FIDDLE My first version of the code is $(text).find("#job2").remove(); didn't work in jsfiddle, but when I added <ul></ul> to the code, it worked like a charm. I have no idea why I did not work with the first instance without ul And I do not see a case where li comes without ul So, 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);​ 
    +3
    source share

    if you want to remove "job2" from the text

     $(text).find("#job2").remove(); 
    +3
    source share

    All Articles