Changing HTML in JavaScript without innerHTML
Let's say my code was something pretty simple like this:
let content = "";
for(let i=0; i<array.length; i++)
content+='<h1>array[i]</h1>';
document.getElementById('some_id').innerHTML = content;
I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.
In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?
Thanks in advance!
javascript html dom innerhtml
add a comment |
Let's say my code was something pretty simple like this:
let content = "";
for(let i=0; i<array.length; i++)
content+='<h1>array[i]</h1>';
document.getElementById('some_id').innerHTML = content;
I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.
In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?
Thanks in advance!
javascript html dom innerhtml
You can usedocument.createElementandnodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.
– Mike Cluck
Nov 14 '18 at 20:20
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know wherearraycomes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example<script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.
– Aakil Fernandes
Nov 14 '18 at 20:24
content+='<h1>array[i]</h1>';will not evaluatearray[i]but instead print it as text.
– connexo
Nov 14 '18 at 20:32
add a comment |
Let's say my code was something pretty simple like this:
let content = "";
for(let i=0; i<array.length; i++)
content+='<h1>array[i]</h1>';
document.getElementById('some_id').innerHTML = content;
I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.
In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?
Thanks in advance!
javascript html dom innerhtml
Let's say my code was something pretty simple like this:
let content = "";
for(let i=0; i<array.length; i++)
content+='<h1>array[i]</h1>';
document.getElementById('some_id').innerHTML = content;
I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.
In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?
Thanks in advance!
javascript html dom innerhtml
javascript html dom innerhtml
asked Nov 14 '18 at 20:17
idudeidude
1,54551836
1,54551836
You can usedocument.createElementandnodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.
– Mike Cluck
Nov 14 '18 at 20:20
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know wherearraycomes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example<script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.
– Aakil Fernandes
Nov 14 '18 at 20:24
content+='<h1>array[i]</h1>';will not evaluatearray[i]but instead print it as text.
– connexo
Nov 14 '18 at 20:32
add a comment |
You can usedocument.createElementandnodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.
– Mike Cluck
Nov 14 '18 at 20:20
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know wherearraycomes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example<script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.
– Aakil Fernandes
Nov 14 '18 at 20:24
content+='<h1>array[i]</h1>';will not evaluatearray[i]but instead print it as text.
– connexo
Nov 14 '18 at 20:32
You can use
document.createElement and nodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.– Mike Cluck
Nov 14 '18 at 20:20
You can use
document.createElement and nodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.– Mike Cluck
Nov 14 '18 at 20:20
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know where
array comes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example <script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.– Aakil Fernandes
Nov 14 '18 at 20:24
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know where
array comes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example <script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.– Aakil Fernandes
Nov 14 '18 at 20:24
content+='<h1>array[i]</h1>'; will not evaluate array[i] but instead print it as text.– connexo
Nov 14 '18 at 20:32
content+='<h1>array[i]</h1>'; will not evaluate array[i] but instead print it as text.– connexo
Nov 14 '18 at 20:32
add a comment |
4 Answers
4
active
oldest
votes
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
add a comment |
You can use the createElement() method
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is an example,
document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>add a comment |
A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:
'beforebegin''afterbegin''beforeend''afterend'
Like this:
document.getElementById("some_id").insertAdjacentElement("afterbegin", content);
Here's a Fiddle example
add a comment |
Creating the element programmatically instead of via HTML should have the desired effect.
const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
while (parent.firstChild)
parent.removeChild(parent.firstChild);
// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++)
const newElem = document.createElement('h1');
newElem.innerText = array[i];
parentElement.appendChild(newElem);
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308130%2fchanging-html-in-javascript-without-innerhtml%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
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
add a comment |
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
add a comment |
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
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
answered Nov 14 '18 at 20:27
NickHTTPSNickHTTPS
532313
532313
add a comment |
add a comment |
You can use the createElement() method
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is an example,
document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>add a comment |
You can use the createElement() method
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is an example,
document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>add a comment |
You can use the createElement() method
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is an example,
document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>You can use the createElement() method
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is an example,
document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>document.body.onload = addElement;
function addElement ()
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>answered Nov 14 '18 at 20:33
onyxonyx
1,036212
1,036212
add a comment |
add a comment |
A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:
'beforebegin''afterbegin''beforeend''afterend'
Like this:
document.getElementById("some_id").insertAdjacentElement("afterbegin", content);
Here's a Fiddle example
add a comment |
A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:
'beforebegin''afterbegin''beforeend''afterend'
Like this:
document.getElementById("some_id").insertAdjacentElement("afterbegin", content);
Here's a Fiddle example
add a comment |
A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:
'beforebegin''afterbegin''beforeend''afterend'
Like this:
document.getElementById("some_id").insertAdjacentElement("afterbegin", content);
Here's a Fiddle example
A flexible and more faster (efficient) way to insert HTML elements using JavaScript's insertAdjacentHTML method. It allows you to specify exactly where to place the element. Possible position values are:
'beforebegin''afterbegin''beforeend''afterend'
Like this:
document.getElementById("some_id").insertAdjacentElement("afterbegin", content);
Here's a Fiddle example
answered Nov 14 '18 at 20:42
Juan MarcoJuan Marco
9139
9139
add a comment |
add a comment |
Creating the element programmatically instead of via HTML should have the desired effect.
const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
while (parent.firstChild)
parent.removeChild(parent.firstChild);
// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++)
const newElem = document.createElement('h1');
newElem.innerText = array[i];
parentElement.appendChild(newElem);
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
add a comment |
Creating the element programmatically instead of via HTML should have the desired effect.
const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
while (parent.firstChild)
parent.removeChild(parent.firstChild);
// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++)
const newElem = document.createElement('h1');
newElem.innerText = array[i];
parentElement.appendChild(newElem);
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
add a comment |
Creating the element programmatically instead of via HTML should have the desired effect.
const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
while (parent.firstChild)
parent.removeChild(parent.firstChild);
// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++)
const newElem = document.createElement('h1');
newElem.innerText = array[i];
parentElement.appendChild(newElem);
Creating the element programmatically instead of via HTML should have the desired effect.
const parent = document.getElementById('some_id');
// clear the parent (borrowed from https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
while (parent.firstChild)
parent.removeChild(parent.firstChild);
// loop through array and create new elements programmatically
for(let i=0; i<array.length; i++)
const newElem = document.createElement('h1');
newElem.innerText = array[i];
parentElement.appendChild(newElem);
edited Nov 15 '18 at 17:31
answered Nov 14 '18 at 20:21
Dr_DerpDr_Derp
435210
435210
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
add a comment |
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
Clearing the child nodes using the while loop I have found is slower if you have a lot of nodes, I have been liking this one liner el.parentNode.replaceChild(el.cloneNode(false), el) the element is cloned with the false flag which makes a copy without any children then the element is replaced with it's leaner self.
– Harry Chilinguerian
Nov 14 '18 at 21:21
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
I did think it seemed slower, but does that handle the case where the child doesn't exist?
– Dr_Derp
Nov 15 '18 at 17:31
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308130%2fchanging-html-in-javascript-without-innerhtml%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You can use
document.createElementandnodeYouWishToExtend.appendChild(nodeYouCreated). For another way to do it all together, you can look at frameworks like React, Angular, Vue, Knockout, etc.– Mike Cluck
Nov 14 '18 at 20:20
Best practices are creating DOM element objects and inserting text into those elements to safeguard against XSS
– charlietfl
Nov 14 '18 at 20:21
ps your hunch that writing html in javascript is "bad" is mostly correct. I don't know where
arraycomes from, but assuming its something users can change, they could sneak in some "unsafe" values. For example<script type="text/javascript">doBadThing()</script>. Unless you're escaping your inputs, or using a library that does, you should never set innerHTML directly with user-originating inputs.– Aakil Fernandes
Nov 14 '18 at 20:24
content+='<h1>array[i]</h1>';will not evaluatearray[i]but instead print it as text.– connexo
Nov 14 '18 at 20:32