How to check if a DIV has an ID

Asked

Viewed 1,366 times

1

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

I can check if he has an ID value, so:

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

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

But what I need is to know if the DIV has a id within it.

EXAMPLE 1: I have the following div

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

JQuery here has to tell me he doesn’t have id

EXAMPLE 2: I have the following div

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

JQuery here has to tell me that the div has one id

You can do it?

  • I don’t understand what you want... to me that what you said you wanted to do, is what you’re doing

  • I changed my question, look if you understand now.

2 answers

3

I think I understand your question, with the 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>
<div class="main">...</div>
<div class="main2" id="stack">...</div>

I hope I’ve helped

  • that’s right, thank you

2


The ID is an HTML attribute, so there are several ways to check. Use the one that 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 native attributes of Javascript:

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

.id

Checking the state of the property id, useful for being short to write, 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 fetch the first element with class .menu with an ID. With .querySelectorAll you can receive a collection

if (document.querySelector('.menu[id]'))) {
    // ele tem ID
} else {
    // ele não tem ID
}
  • Very good, thank you.

  • I am trying to do this in a table, but it is going wrong. Could you help me? follow the link https://jsfiddle.net/d0e23b0a/

  • 1

    @Hugoborges using one of the solutions in my answer: https://jsfiddle.net/gbxqwoqk/

  • 1

    vlw thank you so much

Browser other questions tagged

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