0

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.

1
  • Are there any errors in console? Commented Mar 7, 2015 at 3:46

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

1 Comment

Thanks, worked like a charm. Thanks for explaining why as well.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.