skip to Main Content

I’ve tried append ul into a div, but all ul append separately in div’s. I want just child ul into div

Loops selected all ul’s into all div’s separetly.

<li class="first">
    <a>100</a>
    <div></div>
    <ul>
        <li>
            <a>1</a>
        </li>
        <li>
            <a>2</a>
        </li>
        <li>
            <a>3</a>
        </li>
        <li>
            <a>4</a>
        </li>
        <li>
            <a>5</a>
        </li>
        <li>
            <a>6</a>
        </li>
    </ul>
</li>

<li class="first">
    <a>200</a>
    <div></div>
    <ul>
        <li>
            <a>7</a>
        </li>
        <li>
            <a>8</a>
        </li>
        <li>
            <a>9</a>
        </li>
        <li>
            <a>10</a>
        </li>
        <li>
            <a>11</a>
        </li>
        <li>
            <a>12</a>
        </li>
    </ul>
</li>

If I use child() or any jQuery selector all ul’s added into div

Only with the selector all uls are added to all divs and I can’t make a selection because there is no class or id in the code.

HTML code more than 6000 lines, I tried to simplify it as much as I could

I want to this,

<li class="first">
    <a>100</a>
    <div>
        <ul>
            <li>
                <a>1</a>
            </li>
            <li>
                <a>2</a>
            </li>
            <li>
                <a>3</a>
            </li>
            <li>
                <a>4</a>
            </li>
            <li>
                <a>5</a>
            </li>
            <li>
                <a>6</a>
            </li>
        </ul>
    </div>
</li>

<li class="first">
    <a>200</a>
    <div>
        <ul>
            <li>
                <a>7</a>
            </li>
            <li>
                <a>8</a>
            </li>
            <li>
                <a>9</a>
            </li>
            <li>
                <a>10</a>
            </li>
            <li>
                 <a>11</a>
            </li>
            <li>
                <a>12</a>
            </li>
        </ul>
    </div>
</li>

I guess solved it with each and children,

$(".first li").each(function () {
    if ($(this).children().find("ul").length > 0) {
        ...
    }
}

2

Answers


  1. You can use jQuery’s each() method to iterate over each li element and find the ul element that is a direct child of the li. Then, you can move that ul element inside the corresponding div element using the appendTo() method.

    Login or Signup to reply.
  2. As hamdi suggested, using each function in jquery is the simplest of way to do it.

    $.each($('.first'), function (indexInArray, valueOfElement) {          
       $(valueOfElement).find("ul").appendTo($(valueOfElement).find('div'))
     });
    

    This is a small example that I had used.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search