jQuery.get("ajax.php", function(data)
{
$(data).find("div[id^='feed']").each(function() //Find every div with id starting with feed in AJAX response
{
$('#' + $(this).attr("id")).remove();
});
$("#newsfeed").prepend(data);
});
This works for some divs that fit this description in the ajax response, but not all. Thanks in advance.
Just to make it clear, I want to send out an AJAX request for HTML, itterate through all divs in the response. If they share an id with something already in the DOM AND the id starts with ‘feed’, remove them. Then append the AJAX to the top of newsfeed. Sorry if I didn’t properly explain that before.
I think the problem is with this part:
When you pass a string of html to jQuery, like you do with
$(data), jQuery creates DOM elements to match the string (these elements are initially detached from the document) and then returns a jQuery object containing only the top-level elements. That is, if your string contained nested elements all of the elements get created but only the top-level ones are returned in the jQuery object..find("div[id^='feed']")then looks for div elements that are descendants of the elements in the jQuery object created in the previous step, so it will not match any top-level elements.The
.filter()method lets you filter the top-level elements, so you could do something like this:Within the
.each()you can saythis.idrather than$(this).attr("id").Some example html may help clarify what I tried to explain above. Given:
(ignoring the line-break which is there only for readability)
Then
$(data)will create all five divs but return a jQuery object containing only the ‘feed1’ and ‘abc’ divs because they are the only top-level ones.$(data).find("div[id^='feed']")returns a jQuery object containing only the ‘feed2’ and ‘feed3’ divs, because they are the only descendants of the elements in the$(data)jQuery object.$(data).filter("div[id^='feed']")returns a jQuery object containing only the ‘feed1’ div.EDIT: you could probably simplify it with something like this:
This creates a completely empty div as a container so that you can use
.find()within that container and do away with.filter().