Javascript - Append HTML to container element without innerHTML
To give an alternative (as using DocumentFragment
does not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.
var e = document.createElement('div');
e.innerHTML = htmldata;
while(e.firstChild) {
element.appendChild(e.firstChild);
}
Changing HTML in JavaScript without innerHTML
You can use a DOMParser
and ES6 string literals:
const template = text => (
`
<div class="myClass">
<h1>${text}</h1>
</div>
`);
You can create a in memory Fragment:
const fragment = document.createDocumentFragment();
const parser = new DOMParser();
const newNode = parser.parseFromString(template('Hello'), 'text/html');
const els = newNode.documentElement.querySelectorAll('div');
for (let index = 0; index < els.length; index++) {
fragment.appendChild(els[index]);
}
parent.appendChild(fragment);
Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
Basically you can use whatever template you want because it's just a function that return a string that you can feed into the parser.
Hope it helps
JavaScript array content in html without .innerHTML
var humid = [10, 20, 30, 40];var temp = [50, 60, 70, 80];var container = document.querySelector('.container');for(var i=0; i<4; i++){ container.innerHTML += `<p>Temperature was ${temp[i]} degrees and humidity was ${humid[i]} % `;}
<div class="container">
</div>
How can I append HTML code using JavaScript?
Take a look at this original link for that code where we append to the DOM.
Then you can use string interpolation to add the variables to the code like below
function appendHtml(el, str) { var div = document.createElement('div'); //container to append to div.innerHTML = str; while (div.children.length > 0) { el.appendChild(div.children[0]); }}
let author = "me";let message = "Message...";let time = "15:21";
var html = `<li><span class="author">${author}</span><span class="message">${message}</span><span class="time"><div class="line"></div>${time}</span></li>`;appendHtml(document.body, html);
Append html(text) to element without affecting siblings?
You can use element.insertAdjacentHTML()
to evaluate and append a raw HTML string to an element.
element.insertAdjacentHTML('beforeend', '<p>put me inside at the end</p>');
By changing the position
attribute you can insert before the element, after it, inside it at the beginning, or inside it at the end.
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
Unlike innerHTML
, insertAdjacentHTML()
won't cause the browser won't to re-evaluate the entire DOM node you're injecting into, so form field values will be maintained.
var parentEl = document.getElementById('parent');parentEl.insertAdjacentHTML('beforeend', '<p>this paragraph was inserted at the end of the form without affecting the form field values!<p>');
<form id="parent"> <input type="text" value="insert something after form"><br> <input type="text" value="without affecting the values"><br> <input type="text" value="in the form fields"><br></form>
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: Bob's solution, from the comments. Post your answer, Bob! Get credit for it. :-)
function start() {
var myspan = document.getElementById("myspan");
myspan.onclick = function() { alert ("hi"); };
var mydiv = document.getElementById("mydiv");
var newcontent = document.createElement('div');
newcontent.innerHTML = "bar";
while (newcontent.firstChild) {
mydiv.appendChild(newcontent.firstChild);
}
}
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);
Javascript - div content without innerHTML
You can use nodeValue
to access the value of a node, however the value of a div
. In your example you might have the following HTML...
<div id="myLovelyDiv">This is the text that you want to change</div>
and this script...
var myDiv = getElementById("myLovelyDiv");
myDiv.childNodes[0].nodeValue = "The text has been changed.";
but I fail to see why you wouldn't use
myDiv.innerHTML = "The text has been changed properly.";
Appending html using native javaScript
Well, I know this works:
let elem = document.querySelector ( 'css-selector (id or class)' )
That should give you your element. Then you do this:
elem.innerHTML = elem.innerHTML + myNewStuff;
That'll append your html to the innerHTML of the element. I tried it quickly, it works.
How to insert HTML element via JavaScript?
If you want to attach an image into your div you can do the following:
function spawn1() {
let imageElement = document.createElement('img');
imageElement.setAttribute('src','images/redtarget.png');
imageElement.setAttribute('id', 'imageId'); //Use the id for a CSS selector to style it
let windowDiv = document.getElementById("window");
windowDiv.appendChild(imageElement);
}
Related Topics
Detect All Changes to a ≪Input Type="Text"≫ (Immediately) Using Jquery
Using HTML Script Tags to Code While They Have a Source
How to Get a File or Blob from an Object Url
JavaScript String/Integer Comparisons
Jquery: Get Height of Hidden Element in Jquery
Google Maps API V3: How to Remove All Markers
Check If an Element Contains a Class in JavaScript
Jquery/JavaScript Collision Detection
Best Way to Track Onchange As-You-Type in Input Type="Text"
How to Run a Function When the Page Is Loaded
How to Change Div Content With JavaScript
How to Autosize a Textarea Using Prototype
Execute PHP Function With Onclick