This response is only complementary, the @TobyMosque example is very good, but using element.outerHTML
is not cross-platform (I believe that most engines today support, but there may still be cases that do not support), to solve this we can make an alternative method, would be to clone the element that wants to get the outerHTML
and add it to an element created by document.createElement
, example:
var texto = document.getElementById("texto");
document.getElementById("run").onclick = function() {
var elemento = document.getElementById("test");
var elementoVazio = document.createElement("div");
elementoVazio.appendChild(elemento.cloneNode(true));
texto.value = elementoVazio.innerHTML;
}
<div id="test"><strong>Olá mundo!</strong></div>
<p>
<a id="run" href="#">Pegar outerHTML</a>
</p>
<textarea cols="50" rows="10" id="texto"></textarea>
We can add this method as an alternative and if the browser supports the outerHTML
it will not use it, since it does not have need, to solve we can use the following code:
var divTmp = document.createElement("div");
if ("outerHTML" in divTmp) {
//Código com outerHTML nativo
...
} else {
//Código com cloneNode()
...
}
The code would look something like:
var texto = document.getElementById("texto");
var divTmp = document.createElement("div");
document.getElementById("run").onclick = function() {
var elementoVazio, elemento = document.getElementById("test");
if ("outerHTML" in divTmp) {
texto.value = elemento.outerHTML;
} else {
elementoVazio = document.createElement("div");
elementoVazio.appendChild(elemento.cloneNode(true));
texto.value = elementoVazio.innerHTML;
}
}
<div id="test"><strong>Olá mundo!</strong></div>
<p>
<a id="run" href="#">Pegar outerHTML</a>
</p>
<textarea cols="50" rows="10" id="texto"></textarea>
The TobyMosque code would look something like:
if ("outerHTML" in divTmp) {
function getOuterHTML(menu) {
return menu.outerHTML;
}
} else {
function getOuterHTML(menu) {
var data, el = document.createElement("div");
el.appendChild(menu.cloneNode(true));
data = el.innerHTML;
el = null;
return data;
}
}
var menus = document.querySelectorAll("#menu a");
var outerHTML = [].map.call(menus, getOuterHTML).join("\n");