Check if Attribute('id') Exists in jQuery - javascript

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/

Related

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

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>

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();
}
});
});

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.
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.

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