Why Should Y.Innerhtml = X.Innerhtml; Be Avoided

Why should y.innerHTML = x.innerHTML; be avoided?

This method of "copying" HTML elements from one place to another is the result of a misapprehension of what a browser does. Browsers don't keep an HTML document in memory somewhere and repeatedly modify the HTML based on commands from JavaScript.

When a browser first loads a page, it parses the HTML document and turns it into a DOM structure. This is a relationship of objects following a W3C standard (well, mostly...). The original HTML is from then on completely redundant. The browser doesn't care what the original HTML structure was; its understanding of the web page is the DOM structure that was created from it. If your HTML markup was incorrect/invalid, it will be corrected in some way by the web browser; the DOM structure will not contain the invalid code in any way.

Basically, HTML should be treated as a way of serialising a DOM structure to be passed over the internet or stored in a file locally.

It should not, therefore, be used for modifying an existing web page. The DOM (Document Object Model) has a system for changing the content of a page. This is based on the relationship of nodes, not on the HTML serialisation. So when you add an li to a ul, you have these two options (assuming ul is the list element):

// option 1: innerHTML
ul.innerHTML += '<li>foobar</li>';

// option 2: DOM manipulation
var li = document.createElement('li');
li.appendChild(document.createTextNode('foobar'));
ul.appendChild(li);

Now, the first option looks a lot simpler, but this is only because the browser has abstracted a lot away for you: internally, the browser has to convert the element's children to a string, then append some content, then convert the string back to a DOM structure. The second option corresponds to the browser's native understanding of what's going on.

The second major consideration is to think about the limitations of HTML. When you think about a webpage, not everything relevant to the element can be serialised to HTML. For instance, event handlers bound with x.onclick = function(); or x.addEventListener(...) won't be replicated in innerHTML, so they won't be copied across. So the new elements in y won't have the event listeners. This probably isn't what you want.

So the way around this is to work with the native DOM methods:

for (var i = 0; i < x.childNodes.length; i++) {
y.appendChild(x.childNodes[i].cloneNode(true));
}

Reading the MDN documentation will probably help to understand this way of doing things:

  • appendChild
  • cloneNode
  • childNodes

Now the problem with this (as with option 2 in the code example above) is that it is very verbose, far longer than the innerHTML option would be. This is when you appreciate having a JavaScript library that does this kind of thing for you. For example, in jQuery:

$('#y').html($('#x').clone(true, true).contents());

This is a lot more explicit about what you want to happen. As well as having various performance benefits and preserving event handlers, for example, it also helps you to understand what your code is doing. This is good for your soul as a JavaScript programmer and makes bizarre errors significantly less likely!

Difference between innerText, innerHTML and value?

Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.

When should one use .innerHTML and when document.write in JavaScript

innerHTML can be used to change the contents of the DOM by string munging. So if you wanted to add a paragraph with some text at the end of a selected element you could so something like

document.getElementById( 'some-id' ).innerHTML += '<p>here is some text</p>'

Though I'd suggest using as much DOM manipulation specific API as possible (e.g. document.createElement, document.createDocumentFragment, <element>.appendChild, etc.). But that's just my preference.

The only time I've seen applicable use of document.write is in the HTML5 Boilerplate (look at how it checks if jQuery was loaded properly). Other than that, I would stay away from it.

Why the results of using document.getElementById('').innerHTML and document.write() in a for loop are not the same?

It's simply because with innerHTML you are replacing the content of the element, not adding something to it! So every time your loop iterates it just replaces all the html in last iterations with only the last one!

var arrlist = ["Aron", "Bill", "Camile", "Denn", "Earling", "Fiora", "Gibson"];
var a = arrlist.length;var b = 3;var c = 3;function x() { for (var i = 0; i < b; i++) { var x = b*(c-1) +i; var k = i + 1; if (b*(c-1) +i >= a ) { var x = (b*(c-1) +i)%a; } document.getElementById('listshow').innerHTML = document.getElementById('listshow').innerHTML + "<table border='1' width='200px'><thead><tr><th colspan='2'>" +c+ "th list of names</th></tr></thead> <tbody><tr><th width='30%'>" +k+ "th</th><td width='70%' >"+arrlist[x]+ "</td></tr></tbody></table>"; }}
function y() { for (var i = 0; i < b; i++) { var x = b*(c-1) +i; var k = i + 1; if (b*(c-1) +i >= a ) { var x = (b*(c-1) +i)%a; } document.write("<table border='1' width='200px'><thead><tr><th colspan='2'>" +c+ "th list of names</th></tr></thead> <tbody><tr><th width='30%'>" +k+ "th</th><td width='70%' >"+arrlist[x]+ "</td></tr></tbody></table>"); }}
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width">    <title></title>    <link href="style.css" rel="stylesheet" type="text/css"/>      </head>  <body>    <button onclick='x();'>document.getElementById().innerHTML</button>    <button onclick='y();'>document.write()</button>    <div id="listshow"></div>  </body></html>

JS DOM innerHTML Value not changing HTML

Use it like this:

var day1max = document.getElementById("todayMax");
var day1min = document.getElementById("todayMin");
var day1current = document.getElementById("todayCurrent");
var day1img = document.getElementById("todayIcon");
var day1title = document.getElementById("todayTitle");
var day1desc = document.getElementById("todayDesc");

day1max.innerHTML = today.max;
day1min.innerHTML = "today.min";
day1current.innerHTML = today.current;
day1img.setAttribute("src", today.icon);
day1title.innerHTML = today.title;
day1desc.innerHTML = today.description;

In a loop, innerHTML inserts only the last element called

The reason why this is not working is because you enter the infinite loop in a blocking state, meaning that the interval is never entered as the browser is busy looping. Imagine the browser can only do one thing at a time, as in a single thread, so the loop is it, and cannot do anything else until it's done, and in your case it never.

Basically, if you put a setInterval() inside loop without clear it then the setInterval never stop and that mean the loop is infinite so it never complete.

Instead of that, put the loop inside the setInterval() will do the job. Let try this:

const contentsDownDate = document.querySelectorAll(".countDown");
nbElement = contentsDownDate.length-1;
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();

// Update the count down every 1 second
x = setInterval(function() {
for (i=0; i<=nbElement; i++){
// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Output the result in an element with id="demo"
contentsDownDate[i].innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
contentsDownDate[i].innerHTML = "EXPIRED";
}
}
}, 1000);


Related Topics



Leave a reply



Submit