Text for div 2
<...">

JQuery / javascript filtering an html object from an ajax response

I have this html part:

<div id="1"> <div class="text"> Text for div 2 </div> <img src="images/image1.jpg"></img> </div> <div id="2"> <div class="text"> Text in div 2 </div> <img src="images/image2.jpg"></img> </div> 

Which I grab for a simple .ajax-call

 var html = $.ajax({ url: "htmlsnippet.html", cache: false, async: false, dataType: "html" }).responseText; 

If I filter it with:

 var htmlFiltered = $(html).filter("#1"); 

it works fine, I get the whole div with id = "1",
but if i use:

 var htmlFiltered = $(html).filter("#1 .text"); 

The htmlFiltered variable is an empty object. I cannot understand what I am doing wrong.

+4
source share
3 answers

You should save it this way:

 $.ajax({ url: "htmlsnippet.html", cache: false, async: false, dataType: "html", success: function(data){ html = data; } } 

EDIT: Your way to get html works, but it is not recommended.
You cannot capture your last element because you are using filter instead of find , so you should have:

 var htmlFiltered = $(html).find("#1 .text"); 

instead

 var htmlFiltered = $(html).filter("#1 .text"); 

The W3C also recommends not having numeric identifiers.

EDIT 2 : this should work:

 var htmlFiltered = $(html).filter("#1").find(".text"); 

Hope this helps. Greetings

+11
source

If you don’t need the special functionality provided by the full $.ajax method, you should give $.load() try:

The .load () method, unlike $ .get (), allows us to specify the part of the remote document to be inserted. This is achieved by the special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is considered a jQuery selector that determines the content to load.

 $('#result').load('ajax/test.html #container'); 

http://api.jquery.com/load/#loading-page-fragments

+3
source

This works for me:

 $.get(url,function(content) { var content = $(content).find('div.contentWrapper').html(); ... } 
0
source

All Articles