treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] select parent but not its children

  • I have a list of items like this:

      <div id="content">
    
          <div class="element">
    
              <div class="title">Fight club </div>
    
              <div class="year">1999 </div>
    
          </div>
    
          <div class="element">
    
              <div class="title">Life of Pi </div>
    
              <div class="year">2012</div>
    
          </div>
    
      </div>
    

    and I want to put all the elements in an array and loop through them but just the items with the class element without their children.

      elements = $("#content").children('.element');
      console.log(searchElements[0]');
    

    but it gives the right length of array but its index contains the element with its children and I can't addClass for example, gives me an error. It drives me crazy....

  • I don't get it. With its children? I think it's more the issue that $(...)[0] gives you a node object instead of a jQuery object. Try $(...).eq(0) instead.

  • @CrocoDillon check this simple jsFiddle and the comments. I can select an element with a click function but I want also to be able to select elements using they keyboard keys. In this example I try to select just the first element pressing any key.

    note: in order for keydown function to work result window should be active by clicking anywhere in it. Also check the logs on the console.

  • searchElements.eq(0).addClass('selected'); or $(searchElements[0]).addClass('selected');, I need sleep. If you need any more help I'll be back tomorrow!

  • no worries, with your latest comment I understood what I was doing wrong. Time for me to sleep also. Thanks