Catch the children directly from ul

Asked

Viewed 33 times

-1

I need to analyze the direct children of a ul give what I’m doing clone() I’m just not getting any results.

HTML

<ul id="menu">
  <li>Menu 1 </li>
  <li> Menu 2 
     <ul>
       <li>Sub-Menu 1</li>
       <li>Sub-Menu 2</li>
     </ul>
  </li>
  <li>Menu 3 </li>
</ul>

JS

function menu(){
    clone = $( "#menu").clone();
    clone.children("> li").each(function() {
        if($(this).find("ul").length > 0){
            $(this).append("<span>Adiconar Seta</span>");
        } 
    });
}

Can you tell me what I’m doing wrong?

  • I don’t understand what outcome you expect... what would be the purpose of this cloned object?

  • You will clone an entire Menu that will have the same ID as the cloned menu and then put the loose span inside a UL type <ul><span></span><li></li></ul>? It’s all kind of confusing and meaningless... Explain better there what you want to do

1 answer

1


You don’t have to use > on the dial in .children(). If you want to find direct children li of ul cloned, just use the selector li:

clone.children("li").each(function() {

The method .children() seeks only elements in the first level (direct children), ie, .children("li") of the cloned object will find the following li's:

<ul id="menu">
  <li>Menu 1 </li>            ← este
  <li> Menu 2                 ← este
     <ul>
       <li>Sub-Menu 1</li>
       <li>Sub-Menu 2</li>
     </ul>
  </li>
  <li>Menu 3 </li>            ← este
</ul>

After cloning the element, you need to insert it somewhere. In the example below I used .append() to insert at the end of the body.

Your example:

function menu(){
    clone = $( ".menu").clone();
    clone.children("li").each(function() {
        if($(this).find("ul").length > 0){
            $(this).append("<span>Adiconar Seta</span>");
        } 
    });
    
    $("body").append(clone);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="menu()">Clonar</button>
<ul class="menu">
  <li>Menu 1 </li>
  <li> Menu 2 
     <ul>
       <li>Sub-Menu 1</li>
       <li>Sub-Menu 2</li>
     </ul>
  </li>
  <li>Menu 3 </li>
</ul>

The problem is that by cloning <ul id="menu"> you will be duplicating id’s, which is incorrect in HTML, where an id should be unique, although this will not affect the cloning part as the code $("#menu").clone() will always point to the first <ul id="menu">. But it is better to change the id="menu" for class="menu".

Reference:

jQuery . Children()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.