Jquery获取外部html并使用类隐藏元素

问题描述

我有以下标记

<div>
   <div class="myclass">
      <p>some text <span class="my-other-class">abc</span></p>
      <p>some text <span class="my-other-class">abc</span></p>
      <p>some text <span class="my-other-class">abc</span></p>
      ...
   </div>
</div>

我使用以下内容获取元素的外部 html:

var html = $('.myclass').prop('outerHTML');

返回的 html 有一些我想隐藏的类 .my-other-class 元素。在返回的 html 上隐藏这些元素而不是原始元素的语法是什么?所以类似的东西:

$html.('.my-other-class').hide() 

解决方法

您可以克隆元素.myclass,然后在克隆的元素中隐藏.my-other-class

var clone = $('.myclass').clone();

// use .remove() if you want to remove it from the html returned
clone.find('.my-other-class').hide(); 

console.log(clone[0].outerHTML) // or clone.prop('outerHTML')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
   <div class="myclass">
      <p>some text <span class="my-other-class">abc</span></p>
      <p>some text <span class="my-other-class">abc</span></p>
      <p>some text <span class="my-other-class">abc</span></p>
   </div>
</div>