Convert DIV element to String

I have a div element that I want to print on the page when I click the Create button.

Thus, when I click on the create button, I call a function that has: document.getElementById("createdDiv").textContent = document.querySelector("[data-feed]");

This finds my div element and prints on the page [object HTMLDivElement]

However, when I print the element to the console, I get my div element:

<div data-feed class="feed-element" ... ></div>

      

I know the console has a toString function that converts the div element to a string, but I'm not sure how to do this in javascript so that I can print the same string on the page. Any suggestions?

+3


source to share


1 answer


You can use outerHTML

:

document.getElementById("createdDiv").textContent = document.querySelector("[data-feed]").outerHTML;

      

document.getElementById("createdDiv").textContent = document.querySelector("[data-feed]").outerHTML;
      

[data-feed]::before {
  content: 'The source element: ';
  color: #f00;
}

#createdDiv {
  white-space: pre-wrap;
  border: 1px solid #000;
  padding: 0.5em;
  border-radius: 1em;
}
      

<div data-feed="something"><span>Text in here</span> with <em>various</em> <strong>elements</strong></div>
<div id="createdDiv"></div>
      

Run codeHide result


To remove HTML from any childNodes, you can use a function to clone a node, remove the children, and then return only outerHTML

that specific node:



function tagHTMLOnly(elem) {
  var temp = elem.cloneNode();
  while (temp.firstChild) {
    temp.removeChild(temp.firstChild);
  }
  return temp.outerHTML;
}

document.getElementById("createdDiv").textContent = tagHTMLOnly(document.querySelector("[data-feed]"));

      

function tagHTMLOnly(elem) {
  var temp = elem.cloneNode();
  while (temp.firstChild) {
    temp.removeChild(temp.firstChild);
  }
  return temp.outerHTML;
}

document.getElementById("createdDiv").textContent = tagHTMLOnly(document.querySelector("[data-feed]"));
      

[data-feed]::before {
  content: 'The source element: ';
  color: #f00;
}
#createdDiv {
  white-space: pre-wrap;
  border: 1px solid #000;
  padding: 0.5em;
  border-radius: 1em;
}
      

<div data-feed="something"><span>Text in here</span> with <em>various</em>  <strong>elements</strong>
</div>
<div id="createdDiv"></div>
      

Run codeHide result


Literature:

+2


source







All Articles