" + = "" + = "

JavaScript and DOM: Why does "<table>" + = "<tr> <td></td> </tr>" + = "</ table" not work?

In both cases, the contents of the lines are the same. If you do this:

 myDiv.innerHTML += "<table><tr><td>A</td><td>B</td></tr></table>";

You get a table with two columns.

If you do this:

 myDiv.innerHTML += "<table>";
 myDiv.innerHTML += "<tr>";
 myDiv.innerHTML += "<td>A</td>";
 myDiv.innerHTML += "<td>B</td>";
 myDiv.innerHTML += "</tr>";
 myDiv.innerHTML += "</table>";

You get only tags <table></table>. There is no other markup.

Is this because JavaScript changes the value of the content to objects, then we are not adding TD to the Table object? Why is this so?

+3
source share
3 answers

After each innerHTML edit, the browser tries to create a complete set of HTML DOM objects.

So, after the first step you:

<table></table>

Since the end tag is added during error recovery.

<table></table><tr>

, .

... ..

+7

innerHTML . , , ? ? , . , , , ...

var str = "";
str += "<table>";
str += "<tr>";
str += "<td>A</td>";
str += "<td>B</td>";
str += "</tr>";
str += "</table>";

myDiv.innerHTML += str;
+3

DOM innerHTML, (, , ) DOM, , ... .

The result of your test will not always be <table></table>, it will depend on the browser as to how it handles invalid markup ... but in most cases you can expect an invalid result.

This is a demonstration of what it creates innerHTMLas DOM elements .

+2
source

Source: https://habr.com/ru/post/1769173/


All Articles