Excluding div with class from .html()

2019-08-12 04:16发布

If I have:

$activity = $("#activity_contents").html();

is there a way to exclude a list item with a class:

<li class="correct">Something</li>

from the html content in the #activity_contents div displaying?

Thanks.

Update

I have a drag and drop activity where the reset button resets the activity to it's original state using:

<a href="#" id="reset_activity" class="activity_button" title="Clear my answers" >Reset</a>

jQuery

$activity = $("#activity_contents").html();

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

But I don't want any ul li with a class of correct to reset. Is that even possible?

Thanks

2条回答
爷、活的狠高调
2楼-- · 2019-08-12 04:30

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>
查看更多
爷、活的狠高调
3楼-- · 2019-08-12 04:44

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();
});
查看更多
登录 后发表回答