2

I've got a code like this, written just for the problem with the if statement:

   $("ul.pick").click(function(){
      var kid = $(this).find("li.contactIn");
        kid.addClass("current");
        var parent = kid.parent();
         if(parent == $(this))
          {
            parent.addClass("something");
          }
   });

So ul.pick is a menu button, li.contactIn is its child storing the content to be shown. The problem is within the if statement. What have I done wrong? I'm trying to write the code, which will check if currently pulled down li. is the one I'm clicking at the moment. If it is, the code should just pull it up. If not, li. should be pulled down. Thanks in advance :)

Jakub Małojło
  • 251
  • 2
  • 13
  • 3
    You are comparing references. Since $(this) is a brand new jQuery object, they will never every match. To correct it use the .is() function: http://api.jquery.com/is/ – nurdyguy May 17 '16 at 21:52

1 Answers1

3

The issue is that using $(this) calls the jQuery constructor and creates a jQuery object. Comparing objects to each other is always false in JavaScript. You need to compare the actual element.

Here is a full fledged demo showing the click adding the classes

$("ul.pick").click(function(){
    var kid = $(this).find("li.contactIn");
    kid.addClass("current");
    var parent = kid.parent();
    if(parent[0] == this) //compare elements
    {
      parent.addClass("something");
    }
});
.something { color: red; }
.current { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="pick">
  <li class="contactIn">contactIn</li>
</ul>
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • What does [0] mean? And it doesn't seem to work tho – Jakub Małojło May 17 '16 at 22:01
  • @JakubMałojło - `[0]` accesses the underlying native element held by the jQuery object. What doesn't work? – Travis J May 17 '16 at 22:02
  • It just doesn't add the class to the element clicked – Jakub Małojło May 17 '16 at 22:05
  • @JakubMałojło - See the demo, it works just fine. The issue must be somewhere else. – Travis J May 17 '16 at 22:06
  • It surely does. I had a typo. Thanks a lot! Is there any place in the internet where I could read about this awkward [0] sign? I still don't get it and Google isn't very helpful – Jakub Małojło May 17 '16 at 22:11
  • 1
    @JakubMałojło - jQuery internally holds an array of elements that match the selector. The array is exposed through an array-like accessor. Accessing array indexes are done by using `[]` with an index. Using 0 as the index will bring back the first element in the array. In this case, it was our parent element. If there are more than 1 elements, they can also be accessed in this fashion (e.g. [1],[2], etc). There is also the optional jQuery function to do this called `.get()` where it will get back the element as well. `get(0)` is the same as `[0]` value wise. – Travis J May 17 '16 at 22:17