Clone parent item intoto child list with jquery

问题: I want to clone parent item into existing child list like this: <ul id="menu-12" > <li class="menu-item-1"><a href="#">item-1</a> <...

问题:

I want to clone parent item into existing child list like this:

<ul id="menu-12" >
    <li class="menu-item-1"><a href="#">item-1</a>
        <ul class="sub-menu sup-0">
            <li class="menu-item-2"> <a href="#">item-2</a></li>
            <li class="has-child item-3"><a href="#">item-3</a>
                <ul class="sub-menu sup-1">
                    <li class="item-4"><a href="#">item-4</a></li>
                    <li class="has-child item-5"><a href="#">item-5</a>
                        <ul class="sub-menu sup-2">
                            <li class="item-6"><a href="#">item-6</a></li>
                            <li class="item-7"><a href="#">item-7</a></li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>


Ideal output:
item-1
  item-2
  item-3
  item-1(cloned)

    item-4
    item-5
    item-2(cloned)
      item-6
      item-7
      item-5(cloned)

And so on if more. JSFiddle

http://jsfiddle.net/gillyspy/XM4ez/ <- I found something similar but it doesn't work like my "ideal output"


回答1:

JavaScript Solution -

Assuming you want to clone the <a> tag element only.

function foo(element, parentA = null) {
  if (!element) return;
  const ul = element.querySelector(':scope > li > ul'); // inner ul element
  if (!ul) return;
  const parentList = ul.parentNode; // parent li of ul
  const a = parentList.querySelector(':scope > a');
  if (parentA) parentList.insertBefore(parentA, ul);
  const clonedA = a.cloneNode(true); // cloning element
  return foo(ul, clonedA);
}

// pass the reference of first ul element as an argumnent
foo(document.getElementById('menu-12'));
<ul id="menu-12">
  <li class="menu-item-1">
    <a href="#">item-1</a>
    <ul class="sub-menu sup-0">
      <li class="menu-item-2">
        <a href="#">item-2</a>
      </li>
      <li class="has-child item-3">
        <a href="#">item-3</a>
        <ul class="sub-menu sup-1">
          <li class="item-4"><a href="#">item-4</a></li>
          <li class="has-child item-5"><a href="#">item-5</a>
            <ul class="sub-menu sup-2">
              <li class="item-6"><a href="#">item-6</a></li>
              <li class="item-7"><a href="#">item-7</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

  • 发表于 2020-06-27 19:17
  • 阅读 ( 123 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除