Appending HTML String to the Dom

Appending HTML string to the DOM

Use insertAdjacentHTML which is supported in all current browsers:

div.insertAdjacentHTML( 'beforeend', str );

The position parameter beforeend will add inside the element, after its last child.

Live demo: http://jsfiddle.net/euQ5n/

how to append raw html ('string') to html webpage

.appendChild expects the argument it is called with to be a DOM node. So you need to parse the string into the DOM node prior to appending it.

const parser = new DOMParser();const chatContainer = document.getElementById('chat');chatContainer.appendChild(parser.parseFromString(`    <div class="message-data align-center">        <span class="message-data-name" >User joined</span>    </div>`, 'text/xml').firstChild)
<div id='chat'>

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();

// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.

Append html string to DOM without being rendered

All you have to do is modify textContent instead of innerHTML of intended DOM element.

It can be done something like below

var body = document.getElementsByTagName("body")[0];
body.textContent = "<h1>Justification</h1>"

or if you're getting HTML escaped string as in your question then we first need to unescape it as below

var escapedText = "<h1>Justification</h1>";

function unescapedText(escapedText) {
var div = document.createElement("div");
div.innerHTML = escapedText;
return div.textContent;
}

var body = document.getElementsByTagName("body")[0];
body.textContent = unescapedText(escapedText);

when appending the / text as html, it's not load into the DOM

To print </> as text inside HTML, use the respective HTML codes.

< = < and > = >:

document.getElementById("container").innerHTML = "<div></></div>";
console.log(_.escape('</>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js"></script>
<div id="container"></div>

Parse html string and append new div before every heading

One way to go is:

  1. use a RegExp to add the separator div before every heading (<h[1-6]>)
  2. create a div and set its innerHTML to the new HTML string
  3. append the new div to the body

// 0. Original HTML string
const myHTML = "<h2>Lorem</h2><p>ipsupm</p><h3>second header</h3><h3>third header !!</h3>"

// 1. use a RegExp to add the separator div before every heading
const newHTML = myHTML.replace(/(<h[1-6]{1}>)/g, '<div class="separator"></div>$1');

// 2. create a div and set its innerHTML to the new HTML string
const container = document.createElement('div');
container.innerHTML = newHTML;

// 3. append the new div to the body
document.querySelector('body').append(container);
.separator {
height: 2px;
width: 100%;
background-color: #efefef;
}

Append HTML Strings to DOMDocument at start and end of DOMXPath

Here's one way to do it. It makes use of DOMDocumentFragment. Admittedly, it's all a bit convoluted.

Furthermore, one problem with DOMDocumentFragment is that, besides appendXML(), it does not have a counterpart method appendHTML(), which means you can only append HTML to it if it validates as XML.

$html = '<div class="importantnoticediv">
<p class="important-notice-title important-notice-title-1">
NOTICE:
</p>
<p class="important-notice-title important-notice-title-2">
PROFESSIONAL INSTALLATION IS RECOMMENDED!
</p>
</div>';

$dom = new DOMDocument;
// format our output to make it a tad bit easier on the eyes (doesn't help all that much, though)
$dom->formatOutput = true;
// this implicitly adds <html> and <body> tags
$dom->loadHTML( $html );

$xpath = new DOMXpath( $dom );

// notice I appended /p to your original query, so that we get the list of <p> elements inside the "importantnoticediv"
$nodes = $xpath->query('//div[contains(@class, "importantnoticediv")]/p');
// the first <p>
$p1 = $nodes->item( 0 );
// the second <p>
$p2 = $nodes->item( 1 );

// we create a DOMDocumentFragment that is associated with our DOMDocument
$frag = $dom->createDocumentFragment();

// I append your first HTML fragment (must be valid XML)
$frag->appendXML( '<div class="note-icon note-icon-important">
<span><i class="fa fa-exclamation" aria-hidden="true"></i>
</span>
</div>' );
// ... and insert it before our first <p> (parentNode is the "importantnoticediv")
$p1->parentNode->insertBefore( $frag, $p1 );

// frag is now empty again, because we just inserted it(s contents) into the DOMDocument

// we create our second fragment
$frag->appendXML( '<div class="note-text note-text-important"></div>' );

// this time we append it to "importantnoticediv" (i.e. as last child)
// and get the reference to this newly inserted <div>
$insertedNode = $p1->parentNode->appendChild( $frag );

// now we can append (i.e. move) the <p> elements to the newly inserted <div>
$insertedNode->appendChild( $p1 );
$insertedNode->appendChild( $p2 );

// the HTML should now be as desired
echo $dom->saveHTML();


Related Topics



Leave a reply



Submit