DarkKnightFan
DarkKnightFan

Reputation: 1953

Get control/access elements out of HTML js object using jquery

I want to access the element from a HTML string using JQuery.

I have a following AJAX function which returns HTML text on success. I wish to extract only the contents of the tag from that HTML text using Jquery.

suppose i have a variable resp containing HTML content. I want to access the contents of the tag inside this HTML content as below..

var resp = "<html><head></head><body><form action="changePassword" name="fmChangePassword"> .... form elements .... </form></body> </html>"
alert(resp); //this alerts the full HTML content properly                 
alert($(resp).find("form").html()); //trial 1 -- returns NULL
var test = $(resp).find("#changePassword"); //#changePassword is the ID of the form
//alert(test.html());
displayChangePwdWindow(test);   //need to pass the form content here        

I tried using .find() but no success.

Can anyone help me how to do this?

Upvotes: 0

Views: 375

Answers (3)

yosafatade
yosafatade

Reputation: 185

Maybe you need to use .filter() instead of .find(). you can check the Demo: first demo

or maybe if you still want to use .find() you could place the HTML into a wrapper to search from. you can check the Second Demo: second demo

Upvotes: 1

rahul
rahul

Reputation: 7663

may be this can help you

$.ajax({
   type: "POST",
   url: url,
   error: function(jqXHR, textStatus, errorThrown) {
      alert(errorThrown);
   },
   success: function(resp){
      var test = jQuery("<div/>").append(resp).find("#changePassword");
      alert(test.html());
      displayChangePwdWindow(test);  //need to pass the form content here    
   }
});

Upvotes: 0

bipen
bipen

Reputation: 36551

HTML
Create a hidden div in your body....

<div id="DIVID" style="display:none"></div>

AJAX

$.ajax({
        type: "POST",
        url: url,
        error: function(jqXHR, textStatus, errorThrown)
        {alert(errorThrown);},
        success: function(resp){

         $('#DIVID').html(resp);
         var test = $("#changePassword").html();

         displayChangePwdWindow(test);  //need to pass the form content here    
        }
}); 

OR.. you just append it to a body first.. no need to create a hidden div

$.ajax({
        type: "POST",
        url: url,
        error: function(jqXHR, textStatus, errorThrown)
        {alert(errorThrown);},
        success: function(resp){

         $(document.body).append(resp);
         var test = $("#changePassword").html();

         displayChangePwdWindow(test);  //need to pass the form content here    
        }
});

Upvotes: 0

Related Questions