Difference between innerText, innerHTML and value?

The examples below refer to the following HTML snippet: <div id=”test”> Warning: This element contains <code>code</code> and <strong>strong language</strong>. </div> The node will be referenced by the following JavaScript: var x = document.getElementById(‘test’); element.innerHTML Sets or gets the HTML syntax describing the element’s descendants x.innerHTML // => ” // => Warning: This element contains <code>code</code> … Read more

Show/hide ‘div’ using JavaScript

How to show or hide an element: In order to show or hide an element, manipulate the element’s style property. In most cases, you probably just want to change the element’s display property: element.style.display = ‘none’; // Hide element.style.display = ‘block’; // Show element.style.display = ‘inline’; // Show element.style.display = ‘inline-block’; // Show Alternatively, if … Read more

How to get innerHTML of DOMNode?

Compare this updated variant with PHP Manual User Note #89718: <?php function DOMinnerHTML(DOMNode $element) { $innerHTML = “”; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } ?> Example: <?php $dom= new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load($html_string); $domTables = $dom->getElementsByTagName(“table”); // Iterate over DOMNodeList (Implements Traversable) … Read more

Executing elements inserted with .innerHTML

Simplified ES6 version of @joshcomley’s answer with an example. No JQuery, No library, No eval, No DOM change, Just pure Javascript. http://plnkr.co/edit/MMegiu?p=preview var setInnerHTML = function(elm, html) { elm.innerHTML = html; Array.from(elm.querySelectorAll(“script”)).forEach( oldScript => { const newScript = document.createElement(“script”); Array.from(oldScript.attributes) .forEach( attr => newScript.setAttribute(attr.name, attr.value) ); newScript.appendChild(document.createTextNode(oldScript.innerHTML)); oldScript.parentNode.replaceChild(newScript, oldScript); }); } Usage $0.innerHTML = HTML; … Read more

Is it possible to append to innerHTML without destroying descendants’ event listeners?

Unfortunately, assignment to innerHTML causes the destruction of all child elements, even if you’re trying to append. If you want to preserve child nodes (and their event handlers), you’ll need to use DOM functions: function start() { var myspan = document.getElementById(“myspan”); myspan.onclick = function() { alert (“hi”); }; var mydiv = document.getElementById(“mydiv”); mydiv.appendChild(document.createTextNode(“bar”)); } Edit: … Read more