Evan McCoy
Evan McCoy

Reputation: 11

Null style property on DOM element: JavaScript

I am trying to add some custom JavaScript to an Enjin web platform. In the platform's HTML, there is a common element in the forums that I want to change the background color of.

<div class="block-container">...content...</div>

I am attempting to access it with the following JavaScript code:

function onStart() {
for (block in document.getElementsByClassName("block-container")) {
    console.log("block");
    if (block.style != null) {
        console.log("styleNotNull");
        block.style.backgroundColor = "#252525";
    }
}
}window.onload = onStart;

However, when the page loads, it logs the word "block" in the console for each element but does not change the color or log "styleNotNull". If I remove the null checker, it errors out and says that the style property is null. Most of the answers on this topic have been because the element was missing, but that is obviously not the case because the for loop is executing.

Upvotes: 0

Views: 692

Answers (3)

Andrei
Andrei

Reputation: 44600

Pure javascript

Use ordinary for loop:

var blocks = document.getElementsByClassName("block-container");
for (var i = 0; i < blocks.length; i++) {
    var block = blocks[i];
    block.style.backgroundColor = "#252525";
}

Working jsfiddle.

Basically for..in loop iterates through the properties of an object passed. More info here.

JQuery

This could be easily done by jQuery. So just in case here is an example:

$(function() {
    $(".block-container").css("background-color", "#252525");
});

Working jsfiddle.

Upvotes: 1

Matthew Kime
Matthew Kime

Reputation: 754

The for in loop is for enumerating properties but you want to iterate over an array. Use a for loop instead. Or Array.prototype.forEach if it's available to all the browsers you're targetting.

See this post for more info - Loop through an array in JavaScript

Upvotes: 0

Aaron
Aaron

Reputation: 228

In JavaScript, a for..in loop will loop through the object passed, but for each iteration, the iterator variable will be assigned the key of the current element, not the value. So, try this instead:

function onStart() {
    var elements = document.getElementsByClassName("block-container");
    for (key in elements) {
        elements[key].style.backgroundColor = "#252525";
    }
}

window.onload = onStart;

Edit:

For a discussion about whether to use for..in or a typical for loop for arrays in JavaScript, see Why is using "for...in" with array iteration a bad idea?

Upvotes: 0

Related Questions