How to check if a DIV has an ID

1

Is there any way to check if a div has an id, using jQuery?

I can check if it has an ID value, like this:

<div id="main">...</div>

if ($("#main").length){
// resto do código aqui
}

But what I need is to know if DIV has id inside it.

EXAMPLE 1: I have the following div

<div class="menu"></div>

Here jQuery has to tell me that it does not have id

EXAMPLE 2: I have the following div

<div class="menu" id='4'></div>

Here jQuery has to tell me that the div has a id

Can you do this?

    
asked by anonymous 12.04.2017 / 02:10

2 answers

2

The ID is an HTML attribute, so there are several ways to check. Use whichever is most useful:

.attr()

Using the getter of jQuery attributes:

if ($('.menu').attr('id')) {
    // ele tem ID
} else {
    // ele não tem ID
}

.getAttribute()

Using the getter of native JavaScript attributes:

if (el.getAttribute('id')) {
    // ele tem ID
} else {
    // ele não tem ID
}

.id

Checking the property status id , useful for being short of writing, essential in cases where the ID is not the same as the one written in HTML:

if (el.id)) {
    // ele tem ID
} else {
    // ele não tem ID
}

[id]

Using CSS selectors to get the first element with class .menu that has ID. With .querySelectorAll you can receive a collection

if (document.querySelector('.menu[id]'))) {
    // ele tem ID
} else {
    // ele não tem ID
}
    
12.04.2017 / 06:00
3

I think if I understand your question, with attr you can do this

// verifica se a classe main possui um id
if ($(".main").attr("id")){
alert("Classe main tem id");
}
else{
alert("Classe main nao tem id");
}
if($(".main2").attr("id")){
alert("Classe main2 tem id");
}
else{
alert("Classe main2 nao tem id");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="main">...</div>
<div class="main2" id="stack">...</div>

I hope I have helped

    
12.04.2017 / 02:21