按类名对 HTML 元素进行分组

问题描述 投票:0回答:1
javascript html class element group
1个回答
0
投票

提供的代码使用类 foo 将连续段落动态包装在单独的

<div>
元素中,并使用类 wrap:

<style>
  /* Styles for better visualization */
  body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
  }
  
  .wrap {
    background-color: #f0f0f0;
    padding: 10px;
    margin-bottom: 10px;
  }
  
  .foo {
    background-color: #ffff99;
    padding: 5px;
    margin: 5px 0;
  }
</style>
<body>

  <div>
    <p>Text 1</p>
    <p class="foo">Text 2</p>
    <p>Text 3</p>
    <p>Text 4</p>
    <p>Text 5</p>
    <p>Text 6</p>
    <p class="foo">Text 7</p>
    <p class="foo">Text 8</p>
    <p>Text 9</p>
    <p class="foo">Text 10</p>
    <p>Text 11</p>
    <p class="foo">Text 12</p>
    <p class="foo">Text 13</p>
    <p class="foo">Text 14</p>
    <p class="foo">Text 15</p>
    <p>Text 16</p>
  </div>

<script>

function wrapFooElements() {
    //select all paragraphs with class "foo"
    var paragraphs = document.querySelectorAll('p.foo');
    //variable to keep track of the current wrap
    var currentWrap = null;

    //loop through each paragraph with class "foo"
    for (var i = 0; i < paragraphs.length; i++) {
        var paragraph = paragraphs[i];
        
        //check if a new wrap is needed or if the current wrap can be reused
        if (!currentWrap || paragraph.previousElementSibling !== currentWrap) {
            //create a new wrap element
            currentWrap = document.createElement('div');
            currentWrap.classList.add('wrap');
            //insert the wrap before the current paragraph
            paragraph.parentNode.insertBefore(currentWrap, paragraph);
        }
        
        //move the paragraph inside the current wrap
        currentWrap.appendChild(paragraph);
    }
}

// Call the function to wrap paragraphs with class "foo"
wrapFooElements();
</script>

© www.soinside.com 2019 - 2024. All rights reserved.