Friday, 15 June 2012

javascript - Converting DIV element into String -



javascript - Converting DIV element into String -

i have div element want printed on page when click create button.

thus, when click create phone call function has: document.getelementbyid("createddiv").textcontent = document.queryselector("[data-feed]");

this finds div element , prints page [object htmldivelement]

however, when print element console, div element:

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

i know console has tostring function converts div element string not sure how in javascript can print same string page. suggestions?

you utilize outerhtml:

document.getelementbyid("createddiv").textcontent = document.queryselector("[data-feed]").outerhtml;

class="snippet-code-js lang-js prettyprint-override">document.getelementbyid("createddiv").textcontent = document.queryselector("[data-feed]").outerhtml; class="snippet-code-css lang-css prettyprint-override">[data-feed]::before { content: 'the source element: '; color: #f00; } #createddiv { white-space: pre-wrap; border: 1px solid #000; padding: 0.5em; border-radius: 1em; } class="snippet-code-html lang-html prettyprint-override"><div data-feed="something"><span>text in here</span> <em>various</em> <strong>elements</strong></div> <div id="createddiv"></div>

in order remove html childnodes, utilize function clone node, remove children, , homecoming outerhtml of specific node:

function taghtmlonly(elem) { var temp = elem.clonenode(); while (temp.firstchild) { temp.removechild(temp.firstchild); } homecoming temp.outerhtml; } document.getelementbyid("createddiv").textcontent = taghtmlonly(document.queryselector("[data-feed]"));

class="snippet-code-js lang-js prettyprint-override">function taghtmlonly(elem) { var temp = elem.clonenode(); while (temp.firstchild) { temp.removechild(temp.firstchild); } homecoming temp.outerhtml; } document.getelementbyid("createddiv").textcontent = taghtmlonly(document.queryselector("[data-feed]")); class="snippet-code-css lang-css prettyprint-override">[data-feed]::before { content: 'the source element: '; color: #f00; } #createddiv { white-space: pre-wrap; border: 1px solid #000; padding: 0.5em; border-radius: 1em; } class="snippet-code-html lang-html prettyprint-override"><div data-feed="something"><span>text in here</span> <em>various</em> <strong>elements</strong> </div> <div id="createddiv"></div>

references:

element.outerhtml.

javascript html

No comments:

Post a Comment