I was trying to get an output of my array.
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button').addEventListener('click', function() {
var sidebar = document.getElementById('sidebar');
var isExpanded = false;
sidebar.classList.forEach(function(className) {
if (className == 'expand') {
isExpanded = true;
}
});
if (isExpanded) {
sidebar.classList.remove('expand');
} else {
sidebar.classList.add('expand');
}
isExpanded = !isExpanded;
var contentwrapper = document.getElementById('content-wrapper');
if (isExpanded) {
contentwrapper.classList.add('padding-offset-2');
} else {
contentwrapper.classList.remove('padding-offset-2');
}
var topics = document.getElementById("content-wrapper").children;
console.log(topics);
topics.forEach(function(topic) {
console.log(topic);
})
});
I am getting the error, that topics.forEach is not a function. Can someone help me with that? I have no clue what I am doing wrong. I am trying to learn JS atm. :)
var topics = document.getElementById("content-wrapper").children;
topics
is an HTMLCollection , not an array, and therefore does not have a forEach() method. You need to convert it to an array first.
var topics = document.getElementById("content-wrapper").children;
console.log(topics);
topics give collection of HTMLCollection, Convert it to array.
see this Most efficient way to convert an HTMLCollection to an Array
var topics= [].slice.call(topics);
For each would not work. try using class for the selector.
$.each( topic, function( key, value ) {
alert( key + ": " + value );
// do your stuff here
});
OR
$(".content-wrapper").each(function() {
// do your stuff here
});
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.