I have this code and I want to append the "ul" variable to elements that have the "myselectItems" class.
my problem is here
selectedElement[i].appendChild(ul);
html code
<div ></div>
javascript code
$(document).ready(function () {
let items = [
'fab fa-500px',
'fab fa-accessible-icon',
'fab fa-accusoft',
'fas fa-address-book',
],
ul = document.createElement('select');
ul.setAttribute("id", "myselect");
ul.setAttribute("name", "myselect");
ul.setAttribute("class", "myselect");
items.forEach(item => {
let li = document.createElement('option');
ul.appendChild(li);
li.innerHTML = item;
});
const selectedElement = document.querySelectorAll('.myselectItems');
for (var i = 0; i < selectedElement.length; i ) {
selectedElement[i].appendChild(ul);
}
});
CodePudding user response:
The issue is because you're appending the same select
element each time, so that single instance gets moved between elements.
To fix this you can use cloneNode()
before you append in order to create a new select
instance for each div
.
selectedElement[i].appendChild(ul.cloneNode(true));
Also note that you should remove the id
attribute you set on the select
, otherwise it will be duplicated which is invalid. id
must be unique.
$(document).ready(function() {
let items = [
'fab fa-500px',
'fab fa-accessible-icon',
'fab fa-accusoft',
'fas fa-address-book',
];
var ul = document.createElement('select');
ul.setAttribute("name", "myselect");
ul.setAttribute("class", "myselect");
items.forEach(item => {
let li = document.createElement('option');
ul.appendChild(li);
li.innerHTML = item;
});
const selectedElement = document.querySelectorAll('.myselectItems');
for (var i = 0; i < selectedElement.length; i ) {
selectedElement[i].appendChild(ul.cloneNode(true));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>
Also note that you can simplify the code:
jQuery($ => {
let items = ['fab fa-500px', 'fab fa-accessible-icon', 'fab fa-accusoft', 'fas fa-address-book'];
let selectHtml = `<select name="myselect" >${items.map(t => `<option>${t}</option>`)}</select>`;
$('.myselectItems').append(selectHtml); // jQuery version
//document.querySelectorAll('.myselectItems').forEach(el => el.innerHTML = selectHtml); // plain JS version
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>