How do you search for an element with the same class depending on the number of children?

6

My scenario is as follows, I have two ul with li . The uls have the same class, but I wanted to manipulate only one of them, in the case, which has only a li as a daughter.

Example: link

Example 2:

 <ul class="teste">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

<ul class="teste">
<li>1</li>
</ul>

I need to manipulate only the% with test% that has only 1 child , which in this case is the second.

I thought about selecting all ul , and doing a check with uls , if it was greater than childElementCount , I would apply a CSS in 1 , otherwise, nothing would happen. But I tried to use ul itself and could not make the comparison, I tried childElementCount too.

    
asked by anonymous 21.12.2015 / 16:34

4 answers

3

You can search for the li belonging to .teste which is the only child, then access the parentNode of it.

var itens = document.querySelectorAll(".teste li:only-child");
var listas =[].map.call(itens, function (item, indice) {
  return item.parentNode;
})
console.log(listas);
<ul class="teste">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

<ul class="teste">
  <li>1</li>
</ul>

If you prefer, in jQuery:

var listas = $(".teste li:only-child").parent();
console.log(listas);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ulclass="teste">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

<ul class="teste">
  <li>1</li>
</ul>
    
21.12.2015 / 16:55
2

One way is to use jQuery.filter ()

var $elementos = $(".teste");

var $minhaUl = $elementos.filter(function() {
  return $(this).find('li').length === 1;
});

$minhaUl.css('background', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="teste">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

<ul class="teste">
  <li>1</li>
</ul>
    
21.12.2015 / 16:52
1

I've got follow your js code and added the if you need.

var lista = document.querySelectorAll('.lista');
console.log(lista);
var listaj = $('.lista');
console.log(listaj.size());
$( ".lista" ).each(function( index ) {
 if( $(this).find("li").length == 1)
   //Código aqui apenas 1 item na LI.
});
    
21.12.2015 / 16:50
-2

Try this, put an id in your ul .

<ul id="minhaLista">
    <li>Elemento 1</li>
    <li>Elemento 2</li>
</ul>

To know the size:

  

$ ("#ListList"). length

    
21.12.2015 / 16:49