jQuery
jQuery Check Attribute Exists Or Not Examples
Have you ever wanted to check if attribute exists or not using jQuery for a certain element? In this article, I am going to share with you different ways that you can use to check if specific attribute for an element exists or not using jQuery. Examples follow.
How to use jQuery to Check Attribute Exists or Not – Examples
For example purposes, I am assuming that I have a div in a page with ID and class. I am now going to check if this div has my desired attribute or not when “Check” button is clicked.
Common HTML Source code for all the following examples:
<html> <head> <title>Change Attribute exists or not</title> <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> </head> <body> <div id="my_div" class="my_class">This is some content.</div> <input type="submit" name="check" id="check" value="Check" /> </body> </html>
Example 1: Check if Attribute exists or not using ID
<script type="text/javascript">
$('#check_using_id').click(function() {
if($("#my_div[class]").length)
{
alert('Attribute Exists!');
}
else
{
alert('Attribute DOES NOT Exist!');
}
});
</script>Example 2: Check if Attribute exists or not using Class
<script type="text/javascript">
$('#check_using_class').click(function() {
if($(".my_class[class]").length)
{
alert('Attribute Exists!');
}
else
{
alert('Attribute DOES NOT Exist!');
}
});
</script>As you can see, you can target any attribute by enclosing them in square brackets as indicated in the above examples.
Simple, isn’t it?
Do you know of any other ways to check attribute exists or not URL using jQuery? Feel free to suggest by commenting below.