Yosra MH
Yosra MH

Reputation: 159

br with javascript showed as HTMLBRElement

let br = document.createElement('br');
let tr = tbody.insertRow(tbody.rows.length);
let td = tr.insertCell(tr.cells.length);
td.textContent = item +br; 

The result that I get besides the item is [object HTMLBRElement] instead of the br itself. How can I have a br after the item without using innerHtml ?

Upvotes: 0

Views: 539

Answers (2)

mss
mss

Reputation: 1493

Since you don't want to loose the previous childs, you can use document fragment like this

let br = document.createElement('br');
let tr = tbody.insertRow(tbody.rows.length);
let td = tr.insertCell(tr.cells.length);
const fragment = document.createDocumentFragment();
fragment.appendChild(item); // make sure that item is an html element, if it is a text , wrap it inside span or p or div element
fragment.appendChild(br);
td.appendChild(fragment) // all childs of fragment are now transferred to td  

https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment for more info

Note that I could have directly used appendChild one by one for td, but I didn't because it makes browser render multiple times, but through DocumentFragment, when you add all the child in one go to the td, browser has to render only one time, making your application more efficient with having the same result.

Upvotes: 1

Barmar
Barmar

Reputation: 780974

item + br performs string concatenation, so the br element is converted to a string. Converting an object to a string produces [object PrototypeName].

To add an HTML element, use the appendChild() method.

td.textContent = item;
td.appendChild(br);

Upvotes: 2

Related Questions