How to make js "for" loop more efficient? - javascript

I am wondering how to make the loop below more efficient. On my page it has more iterations than 100, that is why, as you can imagine it is troublesome.
for (var i = 0; i < 1000; i += 1) {
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
document.getElementById('nodeHolder').appendChild(el);
}
Thanx for help in advance.

All I can really suggest is getting a reference to the nodeHolder element outside of the for:
var nodeHolder = document.getElementById('nodeHolder');
for (var i = 0; i < 1000; i += 1) {
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
nodeHolder.appendChild(el);
}
Or perhaps using a document fragment to hold the interim changes/appends and then add that to to the nodeHolder after the loop:
var fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i += 1) {
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
fragment.appendChild(el);
}
document.getElementById('nodeHolder').appendChild(fragment.cloneNode(true));
JS Fiddle showing both approaches (with timing if the console is available).

jQuery way...
var d = '';
for(var i=0;i<1000;i++) d += '<div>Node ' + (i + 1) + '</div>';
$('#nodeHolder').append(d);
Or javascript inside html...
<div id="nodeHolder">
<script>(function() { for(var i=0;i<1000;i++) document.write('<div>Node ' + (i + 1) + '</div>'); })();</script>
</div>

Maybe: You could generate a HTML String in the for loop like:
<div>Node 1</div><div>Node 2</div>
and then set the .innerHTML property of nodeHolder to this string after the whole loop is completed.
(... and let the DOM renderer figure out how to best optimize the action)

In summary:
Cache your DOM selector.
Ditch the for loop, and go for a reverse while loop.
Only append your element to the DOM once. The DOM is almost always the bottleneck.
In this pattern, you can take advantage of a reverse loop:
//Cache the DOM element
var node = document.getElementById('nodeHolder'),
markup = [];
//Run the loop backwards for additional speed
var i = 10000;
while(i--){
markup.push('<div>Node ' + (i + 1) + '</div>');
}
//Reverse the array, join it, then set the innerHTML
node.innerHTML = markup.reverse().join('');​
Working example: http://jsfiddle.net/ZAkMZ/3/
Reverse while loop speed reference: https://blogs.oracle.com/greimer/entry/best_way_to_code_a
jQuery version:
//Cache the DOM element
var node = $('#nodeHolder'),
markup = [];
//Run the loop backwards for additional speed
var i = 10000;
while(i--){
markup.push('<div>Node ' + (i + 1) + '</div>');
}
//Reverse the array, join it, then set the innerHTML
node.append(markup.reverse().join(''));​

You definitely need to use DocumentFragment as suggested by #David Thomas.
The most efficient version as I see is this... cloneNode is always better than createElement, switching between shallow or deep copy (still faster than createEl) as required.
Not that it gives a significant gain but you should shy away from assignments when you can. Store data in variables only when you need to. Of course when it comes to readability it's a different thing.
var fragment = document.createDocumentFragment();
var tplEl = document.createElement('div');
var contentTpl = document.createTextNode('Node ');
for (var i = 1; i <= 1000; i++) {
var curNode = contentTpl.cloneNode(false);
curNode.nodeValue = curNode.nodeValue + i;
tplEl.cloneNode(false).appendChild(curNode);
fragment.appendChild(tplEl);
}
document.getElementById('nodeHolder').appendChild(fragment);
Note that adding the fragment to the nodeHolder adds all childs of fragment as childs to nodeHolder triggering only 1 flow as opposed to 1000 flows in your earlier code.
Reference: Speeding up JavaScript

May be this way:
for (var i = 0; i < 100; i+=1) {
$("<div/>").appendTo("body").attr({"class":'txtHolder'});
$(".txtHolder").append(i+1);
}​

Related

Is setting id with native javascript faster than with jQuery?

The two ways I know to set the id of an element in javascript are as follows:
var myDiv = document.createElement('div');
$(myDiv).attr('id', 'myDiv');
var myDiv = document.createElement('div');
myDiv.id = 'myDiv';
I'm guessing the second one is better because it doesn't use jQuery, is this true?
Yes, the vanilla javascript solution will be the fastest here (although in this case we are talking extreme microseconds).
Function calls are expensive. And when you call .attr, you are making a function call (defined in the jQuery library) which then ends up doing essentially the native method anyways.
As #Vohuman has also pointed out in the comment on this answer, you also have the overhead of even creating the jQuery instance for the elements passed to it. To even begin though with jQuery though, have to include the jQuery library which also takes up time.
You can measure the duration of functions by repeating the execution in a loop. Measure the seconds and calculate the difference. It is about 7.5 times faster. You can execute the measurement right now, right here:
var loops = 100000;
var beforeJQuery = Date.now();
for(var i = 0; i < loops; i++) {
var myDiv = document.createElement('div');
$(myDiv).attr('id', 'myDiv');
}
var beforeVanilla = Date.now();
for(var i = 0; i < loops; i++) {
var myDiv = document.createElement('div');
myDiv.id = 'myDiv';
}
var afterVanilla = Date.now();
var executionTimeJQuery = (beforeVanilla - beforeJQuery);
var executionTimeVanilla = (afterVanilla - beforeVanilla)
console.log(executionTimeJQuery + "ms took the execution of the jQuery method for " + loops + " loops. This is ~" + (executionTimeJQuery / loops) + "ms per execution.");
console.log(executionTimeVanilla + "ms took the execution of the vanilla method for " + loops + " loops. This is ~" + (executionTimeVanilla / loops) + "ms per execution.");
console.log("The vanilla method is " + (executionTimeJQuery / executionTimeVanilla) + " faster than the jQuery method.");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Approximately 10 times faster.
const iterations = 10000;
const myDiv = document.createElement('div');
console.time('jQuery');
for (let i = 1; i < iterations; i++) {
$(myDiv).attr('id', 'myDiv');
}
console.timeEnd('jQuery');
const myDiv2 = $(myDiv);
console.time('jQuery with object');
for (let i = 1; i < iterations; i++) {
myDiv2.attr('id', 'myDiv');
}
console.timeEnd('jQuery with object');
const myDiv3 = document.createElement('div');
console.time('Vanila Javascript');
for (let i = 1; i < iterations; i++) {
myDiv3.id = 'myDiv';
}
console.timeEnd('Vanila Javascript');
jQuery: 41.998ms
jQuery with object: 32.513ms
Vanila Javascript: 4.670ms
Edit:
If you have jQuery in project you can use it without that speed difference is not significant. This micro optimization is not wort it. If you are not making Javascript FPS game :)
Edit2: #Bergi adding createElement in the timing function will not change the results significantly as you can see below.
const iterations = 10000;
console.time('jQuery');
const myDiv = document.createElement('div');
for (let i = 1; i < iterations; i++) {
$(myDiv).attr('id', 'myDiv');
}
console.timeEnd('jQuery');
console.time('jQuery with object');
const myDiv2 = $(document.createElement('div'));
for (let i = 1; i < iterations; i++) {
myDiv2.attr('id', 'myDiv');
}
console.timeEnd('jQuery with object');
console.time('Vanila Javascript');
const myDiv3 = document.createElement('div');
for (let i = 1; i < iterations; i++) {
myDiv3.id = 'myDiv';
}
console.timeEnd('Vanila Javascript');
jQuery: 35.493ms
jQuery with object: 21.310ms
Vanila Javascript: 4.515ms

adding whole total using javascript

function total()
{
var tot = 0;
for(var i = 1; i <= 20; i++)
{
var total_id = "total_" + i;
tot = tot + document.getElementById(total_id).value;
}
document.getElementById(total).value = tot;
}
"this code should display total; i have several total_i id to display my total in each row. then i have display that row total to my total named form"
tot = tot + document.getElementById(total_id).value;
Note that the value of an element is a string, so + here is a string concatenation, not addition (for example, 1 + 1 = 11)
If you want to do addition (1 + 1 = 2), use
tot = tot + parseInt(document.getElementById(total_id).value);
you can replace your code line tot = tot + document.getElementById(total_id).value;
with: tot = tot + parseInt(document.getElementById(total_id).value); as the javascript is taking it as a string not a integr value. We can convert it to integer by using parseInt().
Your immediate problem, as mentioned in another answer, is that you're adding strings, specifically the value property on a DOM element which is a string. You'll find any number of questions on SO about that.
If you have the elements in an array, finding the sum just becomes
function add(a, b) { return a + b; }
function sum(array) { return array.reduce(add); }
sum(elements.map(function(elt) { return +elt.value; });
However, you're also using the anti-pattern of using ID's as a poor-man's way of identifying and referring to DOM elements. It's better just to remember the elements themselves as you create and add them (if in fact that's how they're being created). That way, you don't have to spend the rest of live constructing IDs and adding them to elements and then constructing them again to pass to getElementById to find them again. By "remembering the elements themselves as you create them", I mean instead of doing something like this:
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elt.setAttribute('id', 'total_' + i);
parent.appendChild(elt);
}
or the equivalent in jQuery, do something like
var elements = [];
for (i=0; i<n; i++) {
var elt = document.createElement('div');
elements.push(elt);
parent.appendChild(elt);
}
Now you have the array of elements themselves, and you don't have to poking around with getElementById every time you want to access them.

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

Javascript looping through large dictionary yields unresponsive script

I'm making a firefox addon that appends words with other words in html text. This code works, but when iterating through an enormous dictionary, I get an unresponsive script error.
What is the best way to improve the speed of this loop?
Splitting up the dictionary into smaller objects? Or setting a timeout function?
var brands = {"manykeys" : "manyvalues"};
function replaceWord(){
for (var key in brands){
htmlreplace(key, key + " (" + brands[key] + ")");
}
}
function htmlreplace(a, b, element) {
if (!element) element = document.body;
var nodes = element.childNodes;
for (var n=0; n<nodes.length; n++) {
if (nodes[n].nodeType == Node.TEXT_NODE) {
var r = new RegExp(a, 'g');
nodes[n].textContent = nodes[n].textContent.replace(r, b);
} else {
htmlreplace(a, b, nodes[n]);
}
}
}
replaceWord();
There are some considerations to take. It depends a lot on what you can change or not. One of the bigger improvements you can do is using array instead of key/value object.
var brands = [
['manykeys0000','manyvalues0000'],
['manykeys0001','manyvalues0001'],
['manykeys0002','manyvalues0002'],
['manykeys0003','manyvalues0003'],
['manykeys0004', ...
];
function replaceWord(){
var i, n = brands.length;
for (i = 0; i < n; ++i) {
htmlreplace(brands[i][0], brands[i][0] + " (" + brands[i][1] + ")");
}
}
A couple of other changes should also give a tiny improvement:
1.) Move nodes.length outside the loop.
2.) If suitable pass document.body from replaceWord()
var body = document.body;
...
htmlreplace(brands[i][0], brands[i][0] + " (" + brands[i][2] + ")", body);
function htmlreplace(a, b, element) {
var nodes = element.childNodes, len = nodes.length;
for (var n=0; n < len; ++n) {
Combined quick benchmark on Chrome and Firefox gave a 30-40% increase in speed.
Other edits to test out:
Move var r = new RegExp(a, 'g'); to replaceWord(), and pass it as first argument to htmlreplace() instead of a.
function replaceWord(){
var i, n = brands.length;
for (i = 0; i < n; ++i) {
var r = new RegExp(brands[i][0], 'g');
htmlreplace(r, brands[i].join(' (') + ')', elem);
}
}
If you play with timeout this article might be of interest. It uses
window.postMessage();
to implement a custom setZeroTimeout() but not sure how it will impact your case.
Beside JSPerf etc. use profiling tools in browser, for example in Chrome, which might be better suited for what you do in your code.
I haven't tried, but doing this might work:
function replaceWord(){
for (var key in brands){
(function(key) {
setTimeout(function() {
htmlreplace(key, key + " (" + brands[key] + ")");
}, 0);
})(key);
}
}
The idea is that you postpone the replacing for when the browser has time for it, instead of doing it monolithically and making the browser freeze while it's thinking.
The bottleneck in your code is not the dictionary size, unless it is really big, but the DOM traversal.
Get the text nodes once and then work with them.
var textnodes = $x("//text()", document.body)
function $x(p, context) {
if (!context) context = document;
var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (i = 0; item = xpr.snapshotItem(i); i++) arr.push(item);
return arr;
}
You should see a considerable speed improvement.

.append VS .html VS .innerHTML performance

This site's run a test between the 3 different methods and it seems .html is the fastest, followed by .append. followed by .innerHTML. Can someone explain to me the reasons why?
Here's the site which does the comparison among the three methods.
I have read this this SO question which is related but I don't really understand the given answer, and the question didn't really elaborate much regarding .innerHtml.
I don't understand the following part:
A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').
Can someone simplify this?
All three are slow to me. Modifying the dom on each iteration is slow.
http://jsperf.com/jquery-append-vs-html-list-performance/24
I just added a new test in there:
var html = [];
for (var i = 0; i < len; i++) {
html.push('<div>Test ' + i + '</div>');
}
document.getElementById('list').innerHTML = html.join('');
This is much faster again. :)
My method in Firefox does 26k Ops/sec vs 1,000, 10,000, and 13
That benchmark is worthless. innerHTML is always faster than DOM manipulation.
jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can.
jQuery from benchmark
var html = '';
for (var i = 0; i < len; i++) {
html += '<div>Test ' + i + '</div>';
}
$('#list').html(html);
innerHTML from benchmark
var list = document.getElementById('list');
for (var i = 0; i < len; i++) {
list.innerHTML = list.innerHTML + '<div>Test ' + i + '</div>';
}
The test for innerHTML would be a lot faster if it was written like:
var list = document.getElementById('list');
var html = '';
for (var i = 0; i < len; i++) {
html += '<div>Test ' + i + '</div>';
}
list.innerHTML = html;
http://jsben.ch/#/yDvKH
How can .html be faster than .innerHTML when the .html is using .innerHTML with a lot of extra code? Here .html implementation in jQuery (taken directly from jQuery file).
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
}
As Bart said, innerHTML is always faster than DOM manipulation.
I was testing hyperHTML, so I thought I share my results. I didn't actually run my benchmarks in CodePen originally, and there is an interesting difference in that the jQuery times are much closer to innerHTML running in CodePen.
Chrome:
createFragment 312.80 ms
hyperHTML 253.10 ms
innerHTML 62.70 ms
$.append 183.40 ms
Chrome (extensions off):
createFragment 225.10 ms
hyperHTML 139.80 ms
innerHTML 47.80 ms
$.append 170.90 ms
Firefox:
createFragment 141 ms
hyperHTML 84 ms
innerHTML 25 ms
$.append 90 ms
Edge:
createFragment 422.50 ms
hyperHTML 184.60 ms
innerHTML 44.00 ms
$.append 1629.69 ms
IE11:
createFragment 1180.29 ms
hyperHTML 13315.59 ms //slow fallbacks, IE sucks
innerHTML 125.70 ms
$.append 2382.49 ms
I think it is all pretty simple. JavaScript is not as fast as the browser at parsing and creating elements, because the browser is machine specific compiled code. You can't do better than just handing over the HTML and letting the browser do the work without interruption.
It is possible that some of the performance differences are due to XSS checking, which would seem prudent.
function runbench(){
var data = [];
for (var i = 0; i < 10001; i++) {
data.push("<span>" + i + "</span>");
}
var perf=[];
var t0 = performance.now();
var c = document.createDocumentFragment();
for (var i = 0; i < 10001; i++) {
var e = document.createElement("span");
e.innerHTML = data[i];
c.appendChild(e);
}
document.querySelector('#createFragment').appendChild(c);
document.querySelector('#createFragment').classList='done';
var t1 = performance.now();
perf.push(t1-t0);
var t0 = performance.now();
document.querySelector('#innerHTML').innerHTML = data.join('');
document.querySelector('#innerHTML').classList='done';
var t1 = performance.now();
perf.push(t1-t0);
var t0 = performance.now();
$('#jqhtml').html(data.join(''));
document.querySelector('#jqhtml').classList='done';
var t1 = performance.now();
perf.push(t1-t0);
var t0 = performance.now();
$('#jqappend').append(data.join(''));
document.querySelector('#jqappend').classList='done';
var t1 = performance.now();
perf.push(t1-t0);
var t0 = performance.now();
hyperHTML.bind(document.querySelector('#hyperHTML'))
`${data.map(function (item) {
return "<span>" + item + "</span>";
})}`;
document.querySelector('#hyperHTML').classList='done';
var t1 = performance.now();
perf.push(t1-t0);
var stats = [];
stats.push("<table>")
stats.push("<tr><td>createFrag: </td><td>" + perf[0].toFixed(2) + "</td></tr>");
stats.push("<tr><td>innerHTML: </td><td>" + perf[1].toFixed(2) + "</td></tr>");
stats.push("<tr><td>$.html: </td><td>" + perf[2] .toFixed(2) + "</td></tr>");
stats.push("<tr><td>$.append: </td><td>" + perf[3] .toFixed(2) + "</td></tr>");
stats.push("<tr><td>hyperHTML: </td><td>" + perf[4].toFixed(2) + "</td></tr>");
stats.push("</table>");
$('#performance').html(stats.join(''));
document.querySelector('#performance').classList='done';
}
https://codepen.io/jwhooper/pen/GzKwMV
I think the innerHTML is faster with suggesstion #Brat.
And on creating loop and appending string should be good on using variable first.
It is make your performance more good.
good code:
var html = '';
for (var i = 0; i < len; i++) {
html += '<div>Test ' + i + '</div>';
};
$('#list').append(html);
not efficient code:
for (var i = 0; i < len; i++) {
var html = '<div>Test ' + i + '</div>';
$('#list').append(html);
}
for example: http://jsben.ch/#/yDvKH
I also had a problem with big table redraw (about 10x100 size). It takes about 300ms to redraw whole table.
The reason was not in the jQuery.append() and not in dom.innerHTML, but in appending each element each time.
The fastest way is to concatenate all elements html code and then append it to DOM.
Like this:
function redrawMyTable( myData )
{
var innerHTML = '';
for ( var i = 0; i < myData.length; i++ )
{
innerHTML += createRowFromData( myData[i] );
}
myTableTbody.innerHTML = innerHTML;
}
function createRowFromData( rowData )
{
var rowHTML = '';
for ( var i = 0; i < rowData.length; i++ )
{
rowHTML += createCellFromData( rowData[i] );
}
return rowHTML;
}
function createCellFromData( cellData )
{
//Do everything you need, and return HTMl code as a string
return cellHTML;
}
Now it takes only 20-30 ms (against 300ms :))
6 years later
Point is - don't manipulate the live DOM. Do it outside. Today, it doesn't matter where. You can use a HTML String, a DocumentFragment (which excludes Internet Explorer) or create a new Element but don't add it to the DOM, fill it as you need and THEN add it.
On Chrome and Firefox my observation is that it's all the same run time, give or take a few percent.
Building a long HTML String in chunks that are stored in an array and then join('')-ed is also not necessary any more. Years ago, I measured big time differences. Not today. Point one: there's no recognizable time difference (on Chrome and FF), and point two: the time isn't lost at this point, but in rendering.
my code innerHTML vs fragment
fragment use
running time : 1300~1500ms
innerHTML use
running time : 1800~2000ms
`
const data = [];
for(let i = 0; i < 1000001;i++){
data.push(i);
}
function useInnerHtml(result_wrap){
let text = ''
for(const item of data){
text += '<div>' + item + '</div>';
}
result_wrap.innerHTML = text;
}
function useFragment(result_wrap){
const fragment= new DocumentFragment(); // or document.createDocumentFragment();
for(const item of data){
const div = document.createElement('div');
div.textContent = item;
fragment.appendChild(div);
}
result_wrap.appendChild(fragment);
}
function createData(obj){
let startTime = new Date().getTime();
const targetParentNode = obj.parentNode;
const result_wrap = targetParentNode.querySelector('.result-wrap');
if(result_wrap.hasChildNodes() == false){
if(result_wrap.className.includes('inner-html')){
useInnerHtml(result_wrap);
}else if(result_wrap.className.includes('fragment')){
useFragment(result_wrap, targetParentNode);
}else{
alert('');
}
}else{
alert('click remove button');
}
let endTime = new Date().getTime();
let time = (endTime - startTime);
targetParentNode.querySelector('.running-time').textContent = 'running time : ' + time + 'ms'
}
function removeContent(){
[...document.querySelectorAll('.result-wrap')].map(e=>e.replaceChildren());
}
`
https://codepen.io/joohyoungkim19940805/pen/BaJQeGW

Categories

Resources