0

I am trying to add class using if and else,but its not working beyond if not reaching to else.

$('.headings aside').click(function() {
    if ($(this).children('span').hasClass("fa-caret-up")) {
      $(this).children('span').addClass('borderGap');
      alert("Hello! I am an alert box!!");
    } else {
      alert("Second Alert");
      $(this).children('span').removeClass('borderGap');
    };
});

Thanks in advance

5
  • Please show your html markup. Commented Apr 10, 2015 at 12:39
  • else { alert("Second Alert"); $(this).children('span').removeClass('borderGap'); } => use this (removed ;) Commented Apr 10, 2015 at 12:40
  • Can you please provide html code. Commented Apr 10, 2015 at 12:43
  • It actually works ... but only one at a time: jsfiddle.net/rfornal/LL9j7fzr Commented Apr 10, 2015 at 12:44
  • put $(this).children('span') into a variable, there is no reason to keep looking it up. Commented Apr 10, 2015 at 12:51

2 Answers 2

1

Your code works:

<aside> 
    <span class="no_class">no class</span>
</aside>

$('aside').click(function() {
    if ($(this).children('span').hasClass("fa-caret-up")) {
      $(this).children('span').addClass('borderGap');
      alert("Hello! I am an alert box!!");
    } else {
      alert("Second Alert");
      $(this).children('span').removeClass('borderGap');
    };
});

http://jsfiddle.net/cpyq6a5r/

The thing is, the behaviour will depend on the html markup.

Example: if you have 2 spans

<span class="no_class">no class</span>
<span class="fa-caret-up">no class</span>

it will never go into the "else" statement, because aside has a span with class "fa-caret-up"

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

Comments

0

I you are looking at getting both add and remove applied "on the same click", try ...

$('.headings aside').click(function() {
    if ($(this).children('span').hasClass("fa-caret-up")) {
      $(this).children('span').addClass('borderGap');
      alert("Hello! I am an alert box!!");
    }
    if (!$(this).children('span').hasClass("fa-caret-up")) {
      alert("Second Alert");
      $(this).children('span').removeClass('borderGap');
    }
});

Which will now check for caret and not caret ... in your original code, if any span had a caret, then the else is not run. Here, both conditions are checked independently.

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.