Search code examples
jqueryhide

Jquery get outer html and hide element with class


I have the following markup

<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>

I use the following to get the outer html of an element:

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

The returned html has some elements with class .my-other-class which i want to hide. Whats the syntax to hide those elements on the html returned but not on the original? So something along the lines of:

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

Solution

  • You can clone element .myclass then hide .my-other-class in the cloned element:

    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>