Home > Back-end >  How to put two different elements inside one div with appendChild?
How to put two different elements inside one div with appendChild?

Time:09-19

I've looked up others questions which got nearly the same topic but sadly haven't found a working solution for myself. I want to put two a Elements inside of one created div Element with appendChild but I can't just append them both together, cause it tells me that it only expects one argument.

let view = this.view as Nullable<HTMLElement>;
let link_1 = document.createElement('a');
let link_2 = document.createElement('a');
let link_container = document.createElement('div');
link_container.setAttribute('style', 'display: flex;');

const cont = link_container.appendChild(link_1, link_2);

view?.appendChild(cont);

I would really appreciate a working solution.

CodePudding user response:

Use just appendenter link description here, not appendChild

let view = this.view as Nullable<HTMLElement>;
let link_1 = document.createElement('a');
let link_2 = document.createElement('a');
let link_container = document.createElement('div');
link_container.setAttribute('style', 'display: flex;');

const cont = link_container.append(link_1, link_2);

CodePudding user response:

Create array to store the no of links variable that you want to create and the create for loop to append a child element on single div.

This will be a dynamic approach you can append multiple child elements in single parent.

like this:

let view = this.view as Nullable<HTMLElement>;
let link_1 = document.createElement('a');
let link_2 = document.createElement('a');
let link_container = document.createElement('div');
link_container.setAttribute('style', 'display: flex;');

const links = [link_1, link_2];

links.forEach(link => {
   link_container.appendChild(link);
})

view?.appendChild(cont);
  • Related