Kiran Kumar
Kiran Kumar

Reputation: 31

How to convert HTML string to HTMLDivElement Object in Jquery?

HTML code is returning from api function as a string format.
var div = infoWindow.getContent(); the div variable contains the following code.

<div class="mt">
    <div class="fl">
        <a id="detailsLink" class="jsDetailsLink" href="/profile/369/john">More profile information</a>
    </div>
</div>

.
I want to convert to [object HTMLDivElement] in jQuery. If it is converted into object HTMLDivElement, I can easily change the a href value through JS code.
How to convert that?

Upvotes: 1

Views: 4435

Answers (3)

user617263
user617263

Reputation: 5

You can simply create a dummy object and append your string to that object after that replace HREF value by jQuery.

var str = '<div class="mt"><div class="fl"><a id="detailsLink" class="jsDetailsLink" href="/profile/369/john">More profile information</a></div></div>';
var dummy = $('<div />');
dummy.html(str);
dummy.find('#detailsLink').attr('href', 'http://google.com'); 
alert(dummy.html());
    $('#data').text(dummy.html());

Upvotes: 0

user1823761
user1823761

Reputation:

Consider you have the following string:

var string = '<div class="mt"><div class="fl"><a id="detailsLink" class="jsDetailsLink" href="/profile/369/john">More profile information</a></div></div>';

You can pass it to $ function, and jQuery power will be in your hands:

var $elem = $(string);

Now you can get the link within it:

$elem.find('a').attr('href', 'http://www.google.com/');

And append it to some element:

$elem.appendTo('body');

  • [!] You can check it at this FIDDLE.

Upvotes: 5

GautamD31
GautamD31

Reputation: 28763

Try with .html like

$(".mt").html();

and if you want to change the href value you can try like

$(".jsDetailsLink").attr("href","my_new_href");

you need some practise and see this JQUERY

Upvotes: 0

Related Questions