<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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With