删除子元素,但使用jQuery / javascript保留内容

时间:2018-09-17 09:59:39

标签: javascript jquery html

所以我有一些看起来像这样的HTML:

    <div class="spinning-items">
         <div>
              <ul>
                  <li>
                      Hello, How Are You?
                  </li>
              </ul>
         </div>
    </div>

我需要删除“ spinning-items”-div中的所有元素,但要保留其内容。在这种情况下,“你好,你好吗?”。 所以,我希望它以后看起来像这样:

    <div class="spinning-items">
          Hello, How Are You?
    </div>

任何人都可以向我指出正确的方向,或者为我提供可行的解决方案吗?

谢谢。

3 个答案:

答案 0 :(得分:6)

尝试关注

$(".spinning-items").html($(".spinning-items").text().trim())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spinning-items">
  <div>
    <ul>
      <li>
        Hello, How Are You?
      </li>
    </ul>
  </div>
</div>

如果类spinning-items中有1个以上元素

$(".spinning-items").each((i,e) => $(e).html($(e).text().trim()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spinning-items">
  <div>
    <ul>
      <li>
        Hello, How Are You?
      </li>
    </ul>
  </div>
</div>
<div class="spinning-items">
  <div>
    <ul>
      <li>
        Hello, How Are You Doing?
      </li>
    </ul>
  </div>
</div>

答案 1 :(得分:1)

使用本地javascript,您可以使用regex和trim()删除空白

let k = document.getElementsByClassName('spinning-items')[0].innerHTML;
var rex = /(<([^>]+)>)/ig;
document.getElementsByClassName('spinning-items')[0].innerHTML = k.replace(rex, "").trim();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spinning-items">
  <div>
    <ul>
      <li>
        Hello, How Are You?
      </li>
    </ul>
  </div>
</div>

答案 2 :(得分:0)

$(".spinning-items"")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();    //get the text of element

这只会给您文本