Jousi Jousi - 12 days ago 6
HTML Question

Javascript getElementByClass().foreach function not working

I am trying to get each element of HTML by Class name with JS and then change its height and width according to the value in a

range
object
onchange
.

The browser is showing an error:
document.getElementsByClassName(...).forEach is not a function


But I tried to structure it every way possible and still nothing...

This is how my first js code looked like:

function updateInput(val) {
document.getElementById('valueInput').innerHTML=val; /*This is just to show the value to the user*/
document.getElementsByClassName('oneResult').forEach(functio‌​n changeWidth(element) { element.style.width = val + 'px'; } );
document.getElementsByClassName('oneResult').forEach(functio‌​n changeWidth(element) { element.style.height = val + 'px'; } );
}


Then I tried this:

function updateInput(val) {
document.getElementById('valueInput').innerHTML=val;
function oneResultWH(element) {
element.style.width = val + 'px';
element.style.height = val + 'px';
}
document.getElementsByClassName('oneResult').forEach(oneResultWH);
}


But still no luck..

This is how my PHP looks like:

print '<div class="oneResult" style="background-image:url(Pictures/'.$img.'); height: 100px; width:100px; ">
<a id="word'. $x .'">'. $textConversion[$x] .'</a></div>';


Any input on this matter would be appreciated!

Answer

The browser is showing an error: document.getElementsByClassName(...).forEach is not a function

That's because getElementsByClassName doesn't return an array, it returns an HTMLCollection. They don't have a forEach method.

You can use the one that arrays have like this:

Array.prototype.forEach.call(document.getElementsByClassName("oneResult"), function(element) {
    // Use `element` here
});

Or on modern browsers (or with a shim):

Array.from(document.getElementsByClassName("oneResult")).forEach(function(element) {
    // Use `element` here
});

More:

Comments