4

I have a div element that I want to be printed on the page when I click a Create Button.

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

This finds my div element and prints to 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 into a string but I am not sure how to do this in javascript so I can print the same string to the page. Any suggestions?

1 Answer 1

4

You could 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>

In order to remove HTML from any childNodes, then you could use a function to clone the node, remove the children, and then return only the outerHTML of 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>

References:

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way for outerHTML to only select the parent Div tag? I do not want the descendants.
Do you know why I'm getting TypeError: Undefined is not a function for the line: var temp = elem.cloneNode(); ?
Offhand, no; it doesn't give errors for me. But are we discussing the demo, or your implementation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.