Delete item from a variable that contains a list

1

I have a larger program, but my problem is residing in deleting an item from a variable that contains a list in there and so I created this Fiddle just with the part of my error.

I put 2 alert() to see if the function is executed or not.

var listaHTML = '<li id=\"liItem1\"  class=\"listItem\">item1</li>'
                    + '<li id=\"liItem2\"  class=\"listItem\">item2</li>'
                    + '<li id=\"liItem3\"  class=\"listItem\">item3</li>'
                    + '<li id=\"liItem4\"  class=\"listItem\">item4</li>'
                    + '<li id=\"liItem5\"  class=\"listItem\">item5</li>'
                    + '<li id=\"liItem6\"  class=\"listItem\">item6</li>'
                    + '<li id=\"liItem7\"  class=\"listItem\">item7</li>'
                    + '<li id=\"liItem8\"  class=\"listItem\">item8</li>'
                    + '<li id=\"liItem9\"  class=\"listItem\">item9</li>'
                    + '<li id=\"liItem10\" class=\"listItem\">item10</li>';

alert(listaHTML);


$("#liItem5").remove();

alert(listaHTML);

As you can see, the 2nd alert remains the same as the 1st, but I was trying to make the li with the id=liItem5 removed from the variable

    
asked by anonymous 27.04.2015 / 15:23

1 answer

1

I suggest creating a div where you put this HTML and remove this li by that way. This way HTML is interpreted by the Browser and jQuery can find the element you want. So:

var div = $('<div/>');
var listaHTML = '<li id=\"liItem1\"  class=\"listItem\">item1</li>'
                    + '<li id=\"liItem2\"  class=\"listItem\">item2</li>'
                    + '<li id=\"liItem3\"  class=\"listItem\">item3</li>'
                    + '<li id=\"liItem4\"  class=\"listItem\">item4</li>'
                    + '<li id=\"liItem5\"  class=\"listItem\">item5</li>'
                    + '<li id=\"liItem6\"  class=\"listItem\">item6</li>'
                    + '<li id=\"liItem7\"  class=\"listItem\">item7</li>'
                    + '<li id=\"liItem8\"  class=\"listItem\">item8</li>'
                    + '<li id=\"liItem9\"  class=\"listItem\">item9</li>'
                    + '<li id=\"liItem10\" class=\"listItem\">item10</li>';
div.html(listaHTML);
div.find("#liItem5").remove();
alert(div.html());

jsFiddle: link

The problem you had is that when you use $("#liItem5") you're looking at the DOM for an element with that ID. And it does not exist in the DOM, only in a string within your variable.

    
27.04.2015 / 15:44