jquery 从 html 方法中排除元素

jquery exclude elements from html method

我如何 select 嵌套在 <div class="thewrapper"> 下的所有元素的 html 除了带有 class="excludeme" 的元素?

<div class="thewrapper">
  <div class="excludeme"> some content to exclude.... </div>

  <div class="whatever">
      <span> lots of content and tags </span>
  </div>

  <div class="excludeme"> some content to exclude again.... </div>

  <div class="whatever">
      <span> more content and tags </span>
  </div>     

我一直在摆弄 jquery .not 和 :not 运算符,但无法使其正常工作。例如。以下不起作用:

var pagehtml = $("div[class^='thewrapper']:not(div[class^='excludeme']").html();
var pagehtml = $('div[class^="thewrapper"]').not('[class="excludeme"]').html();
var pagehtml = $("div.thewrapper:not(:has(div.excludeme))").html();
var pagehtml = $('div:not(".excludeme")').html();

您可以使用这个微型 jQuery 插件 I've created for a similar Question 轻松获取元素的内容(文本或 html)排除/忽略具体选择器:

$.fn.ignore = function(sel){
  return this.clone().find(sel||">*").remove().end();
};

var notExcludeme = $(".thewrapper").ignore(".excludeme").html();
console.log(notExcludeme);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="thewrapper">
  <div class="excludeme"> some content to exclude.... </div>

  <div class="whatever">
    <span> lots of content and tags </span>
  </div>

  <div class="excludeme"> some content to exclude again.... </div>

  <div class="whatever">
    <span> more content and tags </span>
  </div> 
  
</div> 

这只是另一个使用 css 选择器的解决方案。由于您尝试以类似的方式进行操作。

$(function() {
  $('.thewrapper :not(.excludeme)').css('background', 'aqua');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="thewrapper">
  <div class="excludeme">
    some content to exclude....
  </div>

  <div class="whatever">
    <span> lots of content and tags </span>
  </div>

  <div class="excludeme">
    some content to exclude again....
  </div>

  <div class="whatever">
    <span> more content and tags </span>
  </div>
</div>