Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 461
Predz Avatar asked Nov 30 '25 15:11

Predz


2 Answers

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');
like image 137
undefined Avatar answered Dec 03 '25 04:12

undefined


Try with:

$('.menuButton').eq(paramvalue).addClass('on');
like image 22
Nelson Avatar answered Dec 03 '25 05:12

Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!