15

I have used the line below in my app. But now I need to parse the html loaded before I show it. Whats the best way to get certain html elements.

$("#div").load("page.html");

Thanks

UPDATED

Now I am using this but having trouble geting the title attribute of a div with the id "div".

function get_title()
{
    $.get("test.html", function(data) {
        var data = $(data);
        var title = $("#div", data).attr("title");

        alert(title);
    });
}

The html in the var data looks like this.

<div id="div" title="title example">
<p>
    Content
</p>
<p>
    Content
</p>
</div>

Thanks again

1
  • Why do you need to parse the HTML? If you only want part of the loaded code to be on the page, use a selector in the URL parameter. Commented Oct 4, 2010 at 15:29

3 Answers 3

24

You can use the semi-equivalent expanded version of $.get(), like this:

$.get("page.html", function(data) {
  var data = $(data);
  //do something
  $("#div").html(data);
});

Note that calling .html(data) in this case is just a shortcut for .empty().append(data).


Or, if post-processing is an option, just use the .load() callback, like this:

$("#div").load("page.html", function() {
  $(this).find(".class").remove(); //just an example
});
9
  • @Nick Craver I have used get method but cannot get the title of a div named "title". How would I do this. Thanks
    – moo
    Commented Oct 4, 2010 at 16:04
  • @moo - how you you mean "named"? What's the <div> tag look like? Commented Oct 4, 2010 at 16:06
  • @Nick Craver I have updated my 1st post. The id is "div" of the <div>
    – moo
    Commented Oct 4, 2010 at 16:13
  • @moo - To get an attribute you need to search the response, since it isn't in the main document yet, for example: $("#div", data).attr("title"); Commented Oct 4, 2010 at 16:16
  • @Nick Craver Thanks so far. OK i have added it and put the value into a alert for testing but im getting undefined in it :/
    – moo
    Commented Oct 4, 2010 at 16:23
5

Instead of calling .load(), you should call $.get to perform an AJAX request and manually process the response.

5
jQuery.ajax({
    url:'your_url',
    type:'get',
    dataType:'html',
    success:function(data)
   { 
       var _html= jQuery(data);
       //do some thing with html eg: _html.find('div').addClass('red')
       jQuery('#target').html(_html);
   }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.