I would like to retrieve a certain tag element with its attributes from the DOM. For example, from
link text
This can be done without any String manipulation.
Instead, you can use the element's internals and build the string yourself from there:
function getTagHTML(el) {
if (!el instanceof HTMLElement) return null;
let result = `<${el.tagName.toLowerCase()}`;
for (const attribute in el.attributes) {
if (el.attributes[attribute].nodeValue)
result += ` ${el.attributes[attribute].name}="${el.attributes[attribute].nodeValue.replace(/"/g, """)}"`
}
result += `>${el.tagName.toLowerCase()}>`;
return result;
}
console.log(getTagHTML(document.getElementById('outer')));
I do not want this
Please note that for self-closing elements like this would give you an unwanted and incorrect closing tag. Feel free to adjust the code accordingly.