user1559555
user1559555

Reputation: 167

Delete all elements that do not possess specific attribute

I have a small document in which each tag have an attribute like

keep="true"

How can I iterate through the whole <body></body> and remove the whole innerHTML of these tags (removing them itself as well) that do not have this attribute set.

I would prefer to use jQuery, if possible.

Upvotes: 1

Views: 102

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263157

You could combine a :not() selector with an Attribute Equals selector:

$(":not([keep='true'])").remove();

Or maybe even a simple Has Attribute selector, depending on your markup semantics:

$(":not([keep])").remove();

Edit: If you want to remove the matched elements but keep their contents, you can chain children() into unwrap() instead:

$(":not([keep])").children().unwrap();

Upvotes: 2

Ram
Ram

Reputation: 144739

keep is not a valid attribute, you can use data-* attribute and try:

$('*:not([data-keep="true"])').empty()

$('div:not([data-keep="true"])').empty()

Upvotes: 1

Related Questions