Rebecca O'Riordan
Rebecca O'Riordan

Reputation: 883

How to remove all the elements with null id

I want to check for ANY element on the page where the id has no value, and then remove them using jQuery's remove().

This is how the id's look when they have no value passed from the CMS:

<iframe id class="iframeCol"...></iframe>
<div id class="sectional">..</div>

How do I target any and all elements where the id is as above?

Upvotes: 1

Views: 150

Answers (5)

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

//Alternate way
$('body').find('*[id=""]').remove();

var removedItems = 
     $('iframe, div')
     .map(
      function(){ if($(this).attr('id') == "") return this}
     )
    .remove()
    .toArray();
console.log("See the removed items");
console.log(removedItems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<iframe id class="iframeCol">Remove this</iframe>
<div id class="sectional">And remove this</div>

<div>Keep this</div>
<div id="foo">And this</div>

<div id="">Remove this</div>

@Rory McCrossan : Thanks for the snippet.

Upvotes: 1

GibboK
GibboK

Reputation: 73918

If you like vanilla JavaScript with no jQuery you can use this:

document.querySelectorAll('[id=""]').forEach(function(item){
    item.parentNode.removeChild(item);
});
<iframe id class="iframeCol">Remove this</iframe>
<div id class="sectional">And remove this</div>

<div>Keep this</div>
<div id="foo">And this</div>

Brief explanation:

Document.querySelectorAll() Select a list of elements using a CSS3 selector.

Array.prototype.forEach() Loop in your selection.

HTML DOM parentNode Property Get the node of the parent node.

Node.removeChild() Removes a child node from the DOM.

Upvotes: 1

guradio
guradio

Reputation: 15555

$('body *').each(function() {
  console.log($(this).attr('id'))
  if ($(this).attr('id') == '') {
    $(this).remove();

  }

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id class="iframeCol" ...></iframe>
<div id class="sectional">..</div>
<div class="sectional">123</div>
<div id='asd' class="sectional">asd</div>

Compare ID if equals blank remove

Upvotes: 1

user1017882
user1017882

Reputation:

Can do it without jQuery, too:

Array.prototype.forEach.call(document.querySelectorAll('[id=""]'), function(node) {
    node.parentNode.removeChild(node);
});

I know you specified the use of jQuery, but it's here just for reference.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use the attribute selector to achieve this:

$('[id=""]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<iframe id class="iframeCol">Remove this</iframe>
<div id class="sectional">And remove this</div>

<div>Keep this</div>
<div id="foo">And this</div>

Upvotes: 4

Related Questions