2

I'm currently running the following code to apply an array of css attributes to mimic jquery (I'm not allowed to use jquery) but the loop is only grabbing the first node:

HTMLElement.prototype.css = function(attr) {
    for(i in attr){
        return this.style[i] = attr[i];
    }
}

button.css({
    'width': '58px',
    'height': '55px',
    'font-family': 'century gothic',
    'font-weight': 'bold',
    'padding-left': '2px',
    'padding-top': '0',
    'outline': 'none'
});

What is wrong with my loop?

4
  • 1
    this should not be tagged jquery because you dont accept jquery solution Commented May 5, 2016 at 7:50
  • nothing is executed after the return which breaks the for loop Commented May 5, 2016 at 7:51
  • "only grabbing the first node" ? Can you make us run the demo ? Commented May 5, 2016 at 7:51
  • @Suazi that's because you are returning inside the loop, so only the first iteration will be completed and only the first element of css will be applied. Commented May 5, 2016 at 7:57

1 Answer 1

2

The function is exited as soon as the first loop executes due to the return statement. Move the return outside of the loop:

HTMLElement.prototype.css = function(attr) {
    for (i in attr) {
        this.style[i] = attr[i];
    }
    return this; // return the original element to enable chaining
}

var button = document.getElementById('foo');
button.css({
    'width': '58px',
    'height': '55px',
    'font-family': 'century gothic',
    'font-weight': 'bold',
    'padding-left': '2px',
    'padding-top': '0',
    'outline': 'none'
});
<button id="foo">Foo</button>

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

3 Comments

Using the CSS style names is fine in this case as they are being applied through bracket notation, not the style object property directly. Either would work though.
Ooh yes.. True!...+1
No problem, glad to help

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.