How to select elements that have a valid id?

Asked

Viewed 165 times

2

How do I select elements that have an id set? For example, inside the section below I have the following:

<section>
    <div class="div"></div>
    <div id=""></div>
    <div id="div2"></div>
    <div></div>
    <div id="div3"></div>
</section>

In the case above, I need to pick up only the 3rd and 5th div that has a valid and not empty id. How can I pick this up at jQuery?

2 answers

3


you can use the following selector: [id][id!='']

var elems = $("[id][id!='']");
console.log(elems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
    <div class="div"></div>
    <div id=""></div>
    <div id="div2"></div>
    <div></div>
    <div id="div3"></div>
</section>

  • Great answer @Tobiasmesquita, I edited only for visualization of the result to be more comfortable for us.

  • It worked right!

2

You can do it this way:

var el = $('[id]:not([id=""])');

console.log(el.get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
    <div class="div"></div>
    <div id=""></div>
    <div id="div2"></div>
    <div></div>
    <div id="div3"></div>
</section>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.