Damien
Damien

Reputation: 4319

using jquery to check if element has class and treat the chained element children individually

Sorry for the confusing question but here's what i'm trying to do. I have a page with multiple (ul) items. I'm using jquery to manipulate the classes of the (ul)'s and (li)'s. What i'm trying to do is treat each (ul) as an individual as oppose to a whole. For example my:

<ul class="bNav">
  <li><a href="#">Home</a></li>
  <li><a href="#">The Artists</a></li>
  <li><a href="#">The Art</a></li>
</ul>

<ul class="bNav opp">
  <li><a href="#">Home</a></li>
  <li><a href="#">The Artists</a></li>
  <li><a href="#">The Art</a></li>
</ul>

What i'm trying to do with my jquery is if the 'opp' class is present then add a certain code to it. If it's not there then do something else. The problem i'm having is that when i do an if check, if the class is present, it will treat all (ul)'s as if they have that class. Here's my code:

if ($('.bNav').is('.opp')) {
    $('.bNav').addClass('nav').wrap('<nav class="navbar navbar-inverse"><div class="navbar-inner">');
} else {
    $('.bNav').addClass('nav').wrap('<nav class="navbar"><div class="navbar-inner">');
}

$('.bNav > li > ul').addClass('dropdown-menu').parent('li').addClass('dropdown').find('a:first').attr('data-toggle', 'dropdown').addClass('dropdown-toggle').append('<span class="caret"></span>');  
$('.bNav ul ul').addClass('dropdown-menu').parent('li').addClass('dropdown-submenu');

Again, the code is treating all (ul)'s as one. so if the class "opp" is present in any of the (ul)'s, then it fires off the if statement for the "opp" class for ALL the (ul)'s. How do i make it work so that each individual (ul) is treated as such? Thanks for your help in advance!

damien

Upvotes: 0

Views: 703

Answers (3)

Anton Morozov
Anton Morozov

Reputation: 1090

Try this:

$('.bNav')
    .addClass('nav')
.filter('.opp')
    .wrap('<nav class="navbar navbar-inverse"><div class="navbar-inner">')
.end().not('.opp')
    .wrap('<nav class="navbar"><div class="navbar-inner">')
;

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 93003

Use an .each loop (and try .hasClass() instead):

$('.bNav').each(function(i,el) {
    if ($(this).hasClass('opp')) {

http://api.jquery.com/each

http://api.jquery.com/hasClass

Upvotes: 2

Dr.Molle
Dr.Molle

Reputation: 117364

From the docs:
.is()
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

Try:

$('.bNav.opp').addClass('nav').wrap('<nav class="navbar navbar-inverse"><div class="navbar-inner">');
$('.bNav').not('.opp').addClass('nav').wrap('<nav class="navbar"><div class="navbar-inner">');

Upvotes: 4

Related Questions