1

I have a div that I want to add a new style to using PrototypeJS. But the following script does not work. What is wrong with it?

<div class='exercise-main'>
</div>

$$('.exercise-main').setStyle({
    backgroundColor: '#900',
    fontSize: '12px'
});
1
  • If my answer helped out out, I'd appreciate it if you accepted my answer. Thanks! ( ^ _ ^ ) Commented Aug 2, 2012 at 20:56

1 Answer 1

4

The $$ function returns an array of all matching elements (if any). setStyle is an element method, not an array method.

There are a few options here.

If you're only ever expecting a single element to be matched, this will work.

$$('.exercise-main')[0].setStyle({color:'red'});

If you want to set the style on every matched element, either of these will work. They're essentially the same.

$$('.exercise-main').each(function(element) {
    element.setStyle({color: 'red'});
});

or

$$('.exercise-main').invoke('setStyle', {color:'red'});

Of course, if your element has an id, you can use the $ function to find just that element. This differs from $$ in that you don't pass it a selector string, but just the string of the id (ie no '#'). Also, this returns just the element or null - not an array - so you can use element methods straight from the returned value, similar to what you were initially attempting.

$('myElementId').setStyle({color:'red'});
Sign up to request clarification or add additional context in comments.

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.