Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if div has id or not?

<div id="cardSlots">
<div class="ui-droppable" tabindex="-1" id="card1">one</div>
<div class="ui-droppable" tabindex="-1" id="card2">two</div>
<div class="ui-droppable" tabindex="-1">three</div>
<div class="ui-droppable" tabindex="-1">four</div>
</div>

<script>
     $(".ui-droppable").each(function () {     
       if($(this).attr("id").length>0)
       {
       alert('here');
       }
    });
</script>

I am trying to loop through class but issue is i have card1 and card2 ids duplicate in that page. but above code seems to work but showing below error.

Uncaught Type Error: Cannot read property 'length' of undefined

I am trying to get ids from the loop which are there.

like image 693
jit Avatar asked Jun 21 '12 11:06

jit


People also ask

How do you check if an element contains an ID?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

Does div have ID?

The id attribute assigns an identifier to the <div> element. The id allows JavaScript to easily access the <div> element. It is also used to point to a specific id selector in a style sheet. Tip: id is a global attribute that can be applied to any HTML element.

How do I find div id?

In JavaScript, you can use getElementById() fucntion to get any prefer HTML element by providing their tag id. Here is a HTML example to show the use of getElementById() function to get the DIV tag id, and use InnerHTML() function to change the text dynamically.

Should every div have an ID?

Only put required elements or attributes in HTML. You do not need to put ID attribute if it is not required, and you can always add ID attribute whenever required. Keeping only required elements in html will make it easy to read, clean, low on size and hence improves performance and speed.


1 Answers

Use attribute selector selector[attribute] to get only the elements that have an ID

$('.myClass[id]')   // Get .myClass elements that have ID attribute

In your case:

$('.ui-droppable[id]').each(function(){
   alert( this.id );
});

jsFiddle demo

like image 75
Roko C. Buljan Avatar answered Oct 24 '22 16:10

Roko C. Buljan