Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery/javascript, filtering html object from ajax response

I have this piece of html:

<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 with 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 just 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 can't figure out what I'm doing wrong.

like image 661
rjm Avatar asked Dec 04 '22 08:12

rjm


1 Answers

You should store it this way:

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

EDIT: Your way of obtaining html works, but it's not recommended.
You can't grab your last element because you're using filter instead of find, so you should have:

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

instead of

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

Also W3C recommends not to have numeric IDs.

EDIT 2: This should work:

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

Hope this helps. Cheers

like image 89
Edgar Villegas Alvarado Avatar answered Feb 23 '23 18:02

Edgar Villegas Alvarado