Jason908 Jason908 - 1 month ago 5
HTML Question

jquery exclude elements from html method

How can I select the html of all elements nested under

<div class="thewrapper">
except ones with 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>




I have been fiddling with jquery .not and :not operators and just cannot get it working. E.g. the following doesn't work:

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

Answer

You could use this micro jQuery plugin I've created for a similar Question to easily get an element's content (text or html) excluding/ignoring a specific selector:

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

Comments