patrick
patrick

Reputation: 11731

converting HTML to DOM object and vice versa in JQuery

I have a form with a textarea like this:

<textarea id="code"><a href='test.html'><img src='test.jpg'></a></textarea>

I'm turning this code into a DOM object like this:

var code=$("#code").val();
var banner=$(code);

when perform this:

alert(banner.html());

I get "<img src='test.jpg'>", I am expecting the full code ("<a href='test.html'><img src='test.jpg'></a>")

When I perform alert(banner.attr('href') I do get 'test.html', which is what I expected, and it indicates the DOM object is correct and complete.

What I eventually want to do is work on the HTML, run some searches on the href, manipulate it, and write the result back in the textarea. Converting it to a DOM seems the most logical step for that.

I put the code in this JSFiddle

What am I missing here and what do I need to do to successfully convert HTML to a DOM, manupulate it, convert it back to HTML and put it back as HTML?

Upvotes: 1

Views: 2605

Answers (3)

Alfgaar
Alfgaar

Reputation: 172

I think that (JSFiddle link) is what you want:

// grab the html source
var code=$("#code").val();

// convert to dom
var banner = $('<div>').html(code);
// find anchor and change attribute
banner.find('a').attr("href","manipulated.html");

// back to source code
code = banner.html()

// set content back into text area
$("#code").val(code); 

Upvotes: 0

Guffa
Guffa

Reputation: 700840

The jQuery object contains the anchor element, but the html method doesn't return the HTML code of the elements in the jQuery element, it returns the HTML code inside the element in the jQuery object.

You can put the element inside another element to get the HTML code:

var html = $('<div>').append(banner).html();

Upvotes: 1

Musa
Musa

Reputation: 97727

<a> is the root element so you get its innerHTML which is the <img>, you probably want the outerHTML, try alert(banner[0].outerHTML); see http://jsfiddle.net/9Awu4/

Upvotes: 1

Related Questions