Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if children has more than 1 div element

Tags:

html

jquery

css

How is it possible to get the number of divs, which are in a li element.

Here is my code but it doesn't work. (Doesn't work mean every img gets the class, also when there is just 1 div inside the li.)

if($('.lookbook ul li').find('div').length > 1){
    $('.lookbook ul li img').addClass('lbcursor');
}

here is my html structure:

<div class="lookbook>
    <ul>
        <li>
            <div><img/></div>
            <div></div>
        </li>
        <li>
            <div><img/></div>
            <div></div>
        </li>
        <li>
            <div></img></div>
        </li>
    </ul>
</div>

the third img shouldn't get the class.

i want the number of divs in the li element and if there are more than 1 divs it should add the class .lbcursor to the img.

i did find a similar answer here : jquery: if children with specific class? but it doesn't work

ah i just recognized, that the if clause is correct. the problem is to which elements i add the class.

like image 977
Timotheus0106 Avatar asked Sep 26 '13 15:09

Timotheus0106


People also ask

How do I check if a div has a child div?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

How can I get second child in jQuery?

grab the second child: $(t). children(). eq(1);

Can a div be a child element?

html - div not allowed as child element of button - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


2 Answers

You need to loop through, and target that element.

$('.lookbook ul li').each(function() {
  var $this = $(this);
  if ($this.find('div').length > 1) { //if looking for direct descendants then do .children('div').length
      $this.find('img').addClass('lbcursor');
  }
});

Fiddle

You can also write this as:

$('.lookbook ul li').each(function() {
  var $this = $(this);
      $this.find('img').addClass(function(){ //using function argument syntax for addClass
          return $this.find('div').length > 1 ? "lbcursor" : "";
      });
});
like image 83
PSL Avatar answered Oct 09 '22 12:10

PSL


Clean and simple using the :has() and the :nth-of-type() selectors.

$('.lookbook ul li:has(div:nth-of-type(2)) img').addClass('lbcursor');

jsFiddle Demo

  • P.S - Like the :nth-of-type() selector, this would work only if the div elements are the direct children of the same element (as seen in your question).
like image 36
Itay Avatar answered Oct 09 '22 10:10

Itay