tags:

views:

54

answers:

3

Hi,

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

+4  A: 

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

SLaks
+4  A: 

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

$.get("page.html", success: 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
});
Nick Craver
@Nick Craver I have used get method but cannot get the title of a div named "title". How would I do this. Thanks
moo
@moo - how you you mean "named"? What's the `<div>` tag look like?
Nick Craver
@Nick Craver I have updated my 1st post. The id is "div" of the <div>
moo
@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");`
Nick Craver
@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
@moo - Do you have an example page we can see? Also do you *need* this before the content is loaded? My second "post-processing" option above would allow `$("#div")` to work...but you should use unique IDs, so that should differ from the element you're loading.
Nick Craver
@Nick Craver I have updated my 1st post and this function is called onClick. Thanks
moo
@moo - What does the `<div>` you're loading look like? Is that *all* that's in this loaded file? e.g. it's a root level element?
Nick Craver
@Nick Craver Updated
moo
@moo - Try this: `$(data).filter("#div").attr("title");`
Nick Craver
@Nick Craver - Thats just the job sir. Thank you very much!!!
moo
@moo - Welcome :)
Nick Craver
A: 
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);
   }
});
Praveen Prasad