Skip to content Skip to sidebar Skip to footer

Excluding Div With Class From .html()

If I have: $activity = $('#activity_contents').html(); is there a way to exclude a list item with a class:
  • Something
  • from the html content in

    Solution 1:

    One approach would be to clone the element, find and remove the .correct descendant element(s), then reset the query using .end() and retrieve the cloned HTML:

    $("#activity_contents").clone().find('.correct').remove().end().html();
    

    You could also do this without cloning the elements, however that would affect the element that currently exists in the DOM. The above method wouldn't removing anything from the DOM whereas the one below would:

    $("#activity_contents").find('.correct').remove().html();
    

    However, based on your update, you could simply just remove the elements directly. There is no need to use the .html() method:

    $("#activity #reset_activity").click(function(e) {
      e.preventDefault();
      $("#activity_contents .correct").remove();
      refreshActivity();
    });
    

    Solution 2:

    Use find() to find particular 'li' with class and setting its display property to 'none'.It just hiding that li. If you want to delete that li then use

    $("#activity_contents").find('li.correct').remove();
    

    html code

    <!DOCTYPE html>
    <html>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    
    
    <script>
        $(document).ready(function () {
            $("#activity_contents").find('li.correct').css('display', 'none');
        });
    
    
    </script>
    
    <body>
       <div id="activity_contents">
           test000
           <ul>
                <li class="correct">Something1</li>
                 <li class="">Something2</li>
                 <li class="">Something3</li>
           </ul>
    
           test111
       </div>
     </body>
    </html>
    

    Post a Comment for "Excluding Div With Class From .html()"