This answer is only complementary, the example from @Tobymosque is very good, but the use of element.outerHTML
is not cross-Platform (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 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
will not use it, because there is no 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>
Tobymosque’s 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");
Thank you, @Paulo Rodrigues... perfect.
– Ricardo Santiago