0

I am trying to get the HTML of an element to use in a template.

I tried using jQuery to create the element and then grab the HTML, but that doesn't seem to do what I thought it would do.

I am able to get most of the HTML string from the new element, but the "checked" attribute doesn't seem to get saved.

I can manually build up the HTML, but I'd rather have a library helper to make sure I don't make any silly typos.

Here is what I am trying to do...

http://jsfiddle.net/Kp8e5/28/

Elijah Manor
  • 17,923
  • 17
  • 72
  • 79

4 Answers4

1

Well, what you are trying to do is very difficult.

As per the jquery documentation on .html() :

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

It is a crap shoot whether or not you will get what you want, and even worse to depend on every browser to do the same thing, try to find some way to use the JQuery's append function or do your template on the back-end.

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
Bob Fincheimer
  • 17,978
  • 1
  • 29
  • 54
0

You can just use outerHTML property:

d = document.getElementById("d");
d.outerHTML = "<p>This paragraph replaced the original div.</p>";

https://developer.mozilla.org/en-US/docs/DOM/element.outerHTML#Browser_compatibility related question: jQuery: outer html()

Community
  • 1
  • 1
Azat
  • 3,754
  • 2
  • 15
  • 13
0

.get() and .map() will sure help you.. ;)

var checkBoxAuto = $("<input />", { 
    id: "idAuto" 
    , type : "checkbox"
    , class: "answer"
    , checked : "checked"
}); 
var checkBoxAutoText = $("<div />")
    .append(checkBoxAuto)

var    outerHtml = checkBoxAuto.map(function(){
        return $(this).parent().html();
    }).get();

alert(outerHtml);

demo

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
-1

Rather then try to convert the html back to a string, just keep it as DOM elements.

Thats what clone is great for:

var checkBoxAuto = $("<input />", { 
    id: "idAuto" 
    , type : "checkbox"
    , class: "answer"
    , checked : true
}); 
var checkBoxAutoDiv = $("<div />").append(checkBoxAuto);

checkBoxAutoDiv.clone().appendTo('#div1');
checkBoxAutoDiv.clone().appendTo('#div2');
PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72