how to check if div has id or not? - javascript

<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 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(this.id) is all you need.
Why will this work?
If the element has an ID, the value will a non-empty string, which always evaluates to true.
If it does not have an ID, the value is an empty string which evaluates to false.
I am trying to get ids from the loop which are there.
To get a list of IDs, you can use .map like so:
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
or use the selector Roko suggests in his answer.

demo http://jsfiddle.net/QRv6d/13/
APi link: http://api.jquery.com/prop/
Please try this, this should help
code
$(".ui-droppable").each(function () {
if($(this).prop("id").length > 0)
{
alert('here');
}
});​

If there is no id attribute attr method will return undefined. Just write:
if($(this).attr("id"))

if(typeof $(this).attr("id") != 'undefined')

var $this = $(this);
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
...
}
If you're going to use $(this) more than once, it's advised to find it once, and put the resulting jQuery object in a local variable.

Related

How can I check whether element exists based on the classname?

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.
Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.
check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}
You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/
Try this:
if($('.classname').length > 0)
{
alert('exist');
}
You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.
You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}
try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Get element with certain ID using .is() method

This should be very simple, but I just can't make it work.
I am trying to find an element with certain ID using .is() method:
http://jsfiddle.net/4hbvgwnv/
<div id="foo">Some text</div>
$(document).ready(function() {
var id = "foo";
alert( $("div").is("#" + id).text() );
}):
But this just won't work. What am I doing wrong?
PS: I know I can select an element with $("#foo"), but I want to use the .is() method.
You need to use filter() which filter elements based the selector. is() will return a Boolean value not the jQuery object, returns true at least one element is matched else returns false.
$(document).ready(function() {
var id = "foo";
alert($("div").filter("#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>
Instead you can simply use selector $("div#" + id) which select div with that particular id. It will only select element is div.
$(document).ready(function() {
var id = "foo";
alert($("div#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>
http://api.jquery.com/is/
.is() returns a boolean, if you check your developer console you got an error showing that "text" isn't valid !
Are you sure that .is() can be used for that intent ?
A solution that might work (kinda weird way to do it tho) : http://jsfiddle.net/4hbvgwnv/1/
$( document ).ready(function() {
var id = "foo";
if($("div").is("#" + id))
alert($("div").text());
});
is() returns a boolean, you should use filter() instead:
$("div").filter("#" + id).text()
That said, if you're searching by id, you don't need to bother with a parent selector at all:
$('#' + foo).text()

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

Check if Attribute('id') Exists in jQuery

How can I check if an attribute Id exists in jQuery?
I searched around and found that this should work:
if ($(this).attr('id').attr('id'))
{
}
I still get this error: TypeError: Object gauge1 has no method 'attr'
This itself will work:
if($(this).attr("id"))
Check existing jsfiddle on the issue: http://jsfiddle.net/rwaldron/wVqvr/4/
Just try it the old way
if (this.id) {
//do something
}
You can use the is method and the Has Attribute Selector:
if ($(this).is('[id]')) {
}
if ($(this).attr('id')){
alert(id);
}
you could also just use the plain js object
if( this.id !== undefined && this.id.length > 0 ){
//todo: use id
}
HTML:
<div class="hey"></div>
<div class="you" id="woah"></div>
<div id="results"></div>​
jQuery:
var id = $('div.hey').attr('id');
if (id) {
// Have an id.
} else {
// Don't have an id.
}
A fiddle: http://jsfiddle.net/NEVYT/

mootools add an id

Is there a method like toggleClass() for and ID in mootools?
$("someid").toggleClass("selectedState"); // add or take away .selectedState to an element
but there is no native .toggleId, or am I not reading this question right. As suggested, use .set("id") or code your own function. if your objective here is to have, say:
formelement.getElement("input[type=submit]").toggleID("submitter");
it can go like so:
<div class="foo">foo</div>
...
Element.implement({
toggleID: function(id) {
return this.set("id", (this.get("id") == id) ? "" : id);
}
});
var el = document.getElement("div.foo");
el.toggleID("foo");
alert(el.get("id")); // foo
el.toggleID("foo");
alert(el.get("id")); // null
Use the Element.set(); method.
$('elementID').set('id', 'newId');
documentation: mootools docs

Categories

Resources