Reputation: 640
let option = document.createElement('option');
option.className = "dropdown-item"
option.innerText = username;
option.setAttribute('data-value',results[username]);
userDropdown[item].add(option);
At some point I come across two similar situations where - at first I add child element using parent.add(child) in dropdown selection which has option children and it worked fine. Another place I have bootstrap drop down with anchor element as child but here parent.add(child) no longer works and threw this error TypeError: userDropdown[item].add is not a function
.Only appendChild works as such below
let option = document.createElement('a');
option.className = "dropdown-item"
option.innerText = username;
option.setAttribute('data-value',results[username]);
userDropdown[item].appendChild(option);
When I do search on the web I dont find any clear answer on how these two are different.Anyone can pls explain it to me?
Upvotes: 1
Views: 193
Reputation: 28987
I add child element using parent.add(child) in dropdown selection
This works because you are invoking the HTMLSelectElement#add
method. It exists only on <select>
elements, not on all nodes, unlike Node#appendChild
.
const selectEl = document.createElement("select");
const divEl = document.createElement("div");
const spanEl = document.createElement("span");
const bodyEl = document.body;
console.log("You can .add to a <select> :", "add" in selectEl);
console.log("You can .add to a <div> :", "add" in divEl);
console.log("You can .add to a <span> :", "add" in spanEl);
console.log("You can .add to a <body> :", "add" in bodyEl);
Upvotes: 2