Home > OS >  Method to add an element via innerHTML
Method to add an element via innerHTML

Time:11-27

const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
    `<div >
        <div aria-required="true"  data-type="">${select.placeholder}</div>    
            <div >${select.option.map(el =>
                    `<div  data-type="firstOption">${el}</div>`
            ).join('')}
        </div>
    </div>`)
)

const eles = document.getElementsByClassName("select");
for (let i = 0; i < eles.length; i  ) {
    myElement.innerHTML = selectItems[i]; ///loop
    eles[i].appendChild(myElement.cloneNode(true));
}

I'm trying to add elements through a loop but an infinite loop occurs

CodePudding user response:

You are trying to access an invalid indess for selectedItems array. You should append all items together to myElement after you should append this updated element to your dom.

I directly appended to body but you can change it.

const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
    `<div >
        <div aria-required="true"  data-type="">${select.placeholder}</div>    
            <div >${select.option.map(el =>
                    `<div  data-type="firstOption">${el}</div>`
            ).join('')}
        </div>
    </div>`)
)

for (let i = 0; i < selectItems.length; i  ) {
    myElement.innerHTML  = selectItems[i];
}

document.body.appendChild(myElement);

CodePudding user response:

You can create your HTML dynamically using JavaScript in a more structured way like below. It will help you in future. Also, you have to append your top element myElement somewhere in the existing HTML doc like here I appended it in the body.

const myElement = document.createElement("div");
let data = [{
  option: [0, 1, 2, 3],
  placeholder: "X"
}, {
  option: [0, 1, 2, 3],
  placeholder: "Y"
}];
data.map((select, i) => {
  const selectEl = document.createElement("div");
  selectEl.className = "select";
  const selectBtn = document.createElement("div");
  selectBtn.innerHTML = select.placeholder;
  selectBtn.className = "selectBtn";
  selectBtn["aria-required"] = true;
  selectBtn["data-type"] = "";
  selectEl.appendChild(selectBtn);
  const selectDropdown = document.createElement("div");
  selectDropdown.className = "selectDropdown";
  select.option.map(x => {
    const optionDiv = document.createElement("div");
    optionDiv.className = "option";
    optionDiv["data-type"] = "firstOption";
    optionDiv.innerHTML = x;
    selectDropdown.appendChild(optionDiv);
  });
  selectEl.appendChild(selectDropdown);
  myElement.appendChild(selectEl);
})

document.body.appendChild(myElement);

  • Related