给元素添加一个父元素,以table为例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <table>
      <tr>
        <th>1</th>
        <th>12</th>
      </tr>
      <tr>
        <td>2dsa1</td>
      </tr>
    </table>
    <table>
      <tr>
        <th>1</th>
        <th>12</th>
      </tr>
      <tr>
        <td>2dsa1</td>
      </tr>
    </table>
    <button onclick="addFather()">加父亲</button>
    <script>
      // 给所有的table添加一个父元素
      function addFather() {
        const eletableArr = document.querySelectorAll("table");
        eletableArr.forEach((item) => {
          var elem = document.createElement("div");
          elem.style.width = "100%";
          elem.style.overflowX = "auto";
          elem.style.background = "#f7f8fa";
          item.parentNode.replaceChild(elem, item);
          elem.appendChild(item);
        });
      }
    </script>
  </body>
</html>

 

posted @ 2021-12-14 15:39  花开丶良人归  阅读(102)  评论(0编辑  收藏  举报