0

I have an HTML page like this <div id="div"></div>

I want do add there two elements (the problem appears with a and button) using JavaScript

a1 = document.createElement("a")
a1.innerText = "element1"
div.appendChild(a1)
a2 = document.createElement("a")
a2.innerText = "element2"
div.appendChild(a2)

The result is <div id="div"><a>element1</a><a>element2</a></div>. It differs from

<div id="div">
    <a>element1</a>
    <a>element2</a>
</div>

The second variant has some space beetween words.

Why does this happen? What should I do in order to get some fixed amount of space (I need it because originally worked with buttons)? What is the proper actions in this situation?

Timofey X
  • 73
  • 5

1 Answers1

2

The spaced-out version has text nodes between the elements. The other version does not.

Usually, one should make sure that one's code is designed such that text nodes are completely irrelevant - whether they exist or not, the code works regardless. This is quite easy to do. Biggest thing to keep in mind that parentNode.childNodes returns a collection of all children, including text nodes, whereas parentNode.children returns a collection of only element children.

If you wanted to add text nodes like in your second code, you can pass text strings to insertAdjacentText:

const div = document.querySelector('div');
// First text node
div.insertAdjacentText('beforeend', `
    `);
a1 = document.createElement("a")
a1.innerText = "element1"
div.appendChild(a1)

// Second text node
div.insertAdjacentText('beforeend', `
    `);

a2 = document.createElement("a")
a2.innerText = "element2"
div.appendChild(a2)

// Third text node
div.insertAdjacentText('beforeend', `

`);

console.log('"' + div.innerHTML + '"');
<div></div>

But that's really weird. While you can do it if you really want to, it doesn't accomplish anything useful.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320