jquery从html方法中排除元素

时间:2016-10-28 19:10:37

标签: javascript jquery html jquery-selectors

如何选择嵌套在<div class="thewrapper">下的所有元素的html,除了class =&#34; excludeme&#34; ?

<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和:不是运营商,只是无法让它运转起来。例如。以下不起作用:

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();

2 个答案:

答案 0 :(得分:0)

你可以使用这个微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> 

答案 1 :(得分:0)

这是使用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>