Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getting an outer HTML does not work?

I try to get the outer HTML in two different ways, based on this question. Unfortunately, none of them is giving the expected result:

HTML:

<div id='my_div'>Hello</div>

JS:

$(function() {
    document.write('[' + $('#my_div').clone().wrapAll("<div />").parent().get(0).innerHTML + ']<br />');
    document.write('[' + (new XMLSerializer().serializeToString(document.getElementById('my_div'))) + ']');
});

The output is:

[
Hello
]
[
Hello
]

I expect the following result: <div id='my_div'>Hello</div>

Live example here

What am I doing wrong ?

like image 382
Misha Moroshko Avatar asked Sep 19 '10 14:09

Misha Moroshko


3 Answers

First, your first example works fine. Take a look at your output in Firebug. Note, that since your output is HTML it is rendered as HTML. Note that there are newlines before and after the HELLO............... because the HELLOs are inside DIVs!

Take a look: alt text


Second w/ jQuery, you could also use the method in my answer to the question you linked to:

var outerHTML =  $('<div>').append( $("#my_div").clone() ).html();

jsFiddle example


This appends a clone of the element in question to a DIV jQuery object and gets the inner HTML of the DIV jQuery object.... which is the outerHTML of the element in question.

The general form of the outerHTML of an element is:

$('<div>').append( $(ElementSelector).clone() ).html();

where ElementSelector is the jQuery selector of the element whose outerHTML you want.


Note: The above adds no new elements to the DOM. $('<div>')...... is never added to the DOM. It remains merely jQuery object independent of the DOM.

like image 95
Peter Ajtai Avatar answered Nov 13 '22 02:11

Peter Ajtai


Here is a function used in the lib pure.js to get the outerHTML:

function outerHTML(node){
    return node.outerHTML || new XMLSerializer().serializeToString(node);
}

And to use it the DOM way:

var html = outerHTML(document.getElementById('my_div'));
like image 21
Mic Avatar answered Nov 13 '22 01:11

Mic


UPDATE With DEMO

   $(function() {
        var html = $('<div>').append($('#my_div').clone()).html();
        $('body').html( htmlspecialchars( '[' + html + ']' ) );
   });
  • htmlspecialchars function
like image 2
Luca Filosofi Avatar answered Nov 13 '22 00:11

Luca Filosofi