Predz
Predz

Reputation: 201

Assign a CSS class to a single existing div class rather than to all of them

I'm not sure if im going about this the right way at all but I'll try to explain what I'm trying to do as best I can.

I have a HTML page which contains a menu. Within that menu there are a number of instances where a specific CSS class is being used. When the page changes, a value is passed via URL which is then used to highlight the selected item and expand a submenu.

The problem I'm having is that when I try to use this value to expand the list at the right point, I cant actually select and add a new CSS class or carry out other operations. Ill post some code below so you can maybe get a better understanding of what I'm talking about and then maybe give an example scenario.

if (param != null) {
    $('.menuButton')[paramvalue].addClass('on');
    $('.menuButton')[paramvalue].slideDown('normal');
}

Thats the javascript part thats giving issues. In the case above, paramvalue could be replaced by a 0 or a 1 etc. This part is reaching the specific class I want to change. I checked this by adding an id to the HTML and retrieving that using:

 alert($('.menuButton')[paramvalue].id);

This returned the correct ID value.

The HTML is as follows:

<div class="menuButton" id="2">Button 1</div>
<div class="subMenu">
    <ul>
    <li><a href="#">Item 1.1</a></li>
    <li><a href="#">Item 1.2</a></li>
    <li><a href="#">Item 1.3</a></li>
 </ul>
</div>
<div class="menuButton" id="3">Button 2</div>
<div class="subMenu">
<ul>
    <li><a href="#">Item 2.1</a></li>
    <li><a href="#">Item 2.2</a></li>
    </ul>
</div>

There is no CSS to go with the id's they were mainly just added for testing. I can post related CSS if necessary but I don't think its part of the problem.

I should mention that, using the following works

$('.menuButton').addClass('on');

so maybe that narrows down the issue.

If you need any other info. just ask.

Thanks for any help.

Upvotes: 2

Views: 393

Answers (3)

Ram
Ram

Reputation: 144689

By using $(selector)[index] you are converting a jQuery object to a DOM Element object which has no addClass method, you can use eq() method instead:

$('.menuButton').eq(paramvalue).addClass('on');
$('.menuButton').eq(paramvalue).slideDown('normal');

You can also chain your methods:

$('.menuButton').eq(paramvalue).addClass('on').slideDown('normal');

Upvotes: 7

Pebbl
Pebbl

Reputation: 36005

You can also do:

$('.menuButton:eq('+paramvalue+')').addClass('on');

Which will have a performance gain over selecting all the elements and then cutting them down to just one selected.

Upvotes: 2

Try with:

$('.menuButton').eq(paramvalue).addClass('on');

Upvotes: 2

Related Questions