How to select elements that have a valid id?

2

How do I select elements that have a defined id? For example, within 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 get just the 3rd and 5th div that has a valid id and not empty. How can I get this in jQuery?

    
asked by anonymous 02.05.2017 / 16:58

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><divclass="div"></div>
    <div id=""></div>
    <div id="div2"></div>
    <div></div>
    <div id="div3"></div>
</section>
    
02.05.2017 / 17:07
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><divclass="div"></div>
    <div id=""></div>
    <div id="div2"></div>
    <div></div>
    <div id="div3"></div>
</section>
    
02.05.2017 / 17:11