Delete item from a variable containing a list

Asked

Viewed 34 times

1

I have a larger program, but my problem is the deletion of an item from a variable that contains a list inside and so I created this Fiddle only with the part of my mistake.

I placed 2 alert() to understand 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 second warning remains the same as the first, but I was trying to get, in this case, the li with the id=liItem5 was removed from the variable

1 answer

1


I suggest you create a div where you put this HTML and remove this li that way. That way HTML is interpreted by the browser and jQuery can find the element you want. That way:

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: http://jsfiddle.net/umd8px2r/1/

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.