i have this list of li with the class name list i need to loop on them and get every 4 list of them and append it to ul inside the div with class name first wrp i make the one with JavaScript and get 4 items but field to append it in ul because the is error called
"Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."
var fristWrp = document.querySelector('.fristWrp'); var list = document.querySelectorAll('.list'); var arrayList = Array.from(list); let iterations = Math.ceil(list.length / 4); for (var i = 0; i < iterations; i++) { var chunk = arrayList.slice(i * 4, (i + 1) * 4); var createUl = document.createElement('ul'); fristWrp.appendChild(createUl); createUl.appendChild(chunk); }
<div class="fristWrp"> </div> <li class='list'>text 1</li> <li class='list'>text 2</li> <li class='list'>text 3</li> <li class='list'>text 4</li> <li class='list'>text 5</li> <li class='list'>text 6</li> <li class='list'>text 7</li> <li class='list'>text 8</li> <li class='list'>text 9</li> <li class='list'>text 10</li>
chunk is an array. It should be
var fristWrp = document.querySelector('.fristWrp');
var list = document.querySelectorAll('.list');
var arrayList = Array.from(list);
let iterations = Math.ceil(list.length / 4);
for (var i = 0; i < iterations; i++) {
var chunk = arrayList.slice(i * 4, (i + 1) * 4);
var createUl = document.createElement('ul');
fristWrp.appendChild(createUl);
chunk.forEach(function(item) {
createUl.appendChild(item);
})
}
You could let the query selector do the hard work for you :nth-child()
var fristWrp = document.querySelector('.fristWrp'); var list = document.querySelectorAll('.list:nth-child(4n+1)'); Array.from(list).forEach((chunk) => { var createUl = document.createElement('ul'); fristWrp.appendChild(createUl); createUl.appendChild(chunk); });
<div class="fristWrp"> </div> <li class='list'>text 1</li> <li class='list'>text 2</li> <li class='list'>text 3</li> <li class='list'>text 4</li> <li class='list'>text 5</li> <li class='list'>text 6</li> <li class='list'>text 7</li> <li class='list'>text 8</li> <li class='list'>text 9</li> <li class='list'>text 10</li>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.