简体   繁体   中英

jQuery .not() doesn't remove element?

I am grabbing a copy of some info from a page, but I do not want to include certain <option> elements that appear inside <select> elements on the page.

Therefore, while I grab all the elements I want and am storing them in the variable fields , I check to see if each element is a <select> and if they have the specific <option> that I don't want.

var field = allFields[i].innerHTML;                      //allFields is the raw HTML I'm iterating through
if ($(field).find("select").length > 0) {                //If the element we're looking at contains a select
  console.log("Found a select. It is in " + field);
  console.log($(field).find(".bad-option");
  field = $(field).not(".bad-option").prop("outerHTML"); //Use .not() to remove the elements which have the .bad-option class
                                                         // (and .prop("outerHTML") is just there to convert it back to a String instead of a jQuery object)
}
console.log("Adding " + field);
fields[i] = field;                                      //Add the HTML, free of any unwanted options, to the `fields` variable

Based on jQuery's documentation , I would expect the .not() function to remove any elements out of field which have the bad-option class. Yet that is not the case at all. When I log field before and after using .not() , it prints out the same thing. See the console output from the code above:

Found a select. It is in <label>Description:&nbsp;<select><option>thing1</option><option class="bad-option">thing2</option></select></label>
-----------------
[jQuery list object size 1, containing an object called option.bad-option]
-----------------
Adding <label>Description:&nbsp;<select><option>thing1</option><option class="bad-option">thing2</option></select></label>

So what's going on? How do I remove an option with a certain class from from within a jQuery object? Why isn't .not() working?

If I need to clarify anything, please let me know. I tried to make this question as specific as possible and would be happy to elaborate on any details further.

The documentation is perhaps a bit confusing: not removes elements from the selection , not the DOM. If you want to remove the elements, then just filter and remove:

const processed = $(field);
processed.filter(".bad-option").remove();
field = processed.prop("outerHTML");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM