×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery - hasAttr checking to see if there is an attribute on an element

Given an HTML element, we have to check whether it contains an attribute or not using jQuery.
Submitted by Pratishtha Saxena, on September 06, 2022

prerequisite: Adding jQuery to Your Web Pages

There is no such thing as 'hasAttr' in jQuery. This is a function of JavaScript. Its returns a Boolean expression (true, false) if the selected element contains an attribute or not. But it is not applicable in jQuery.

Over here we have a different method called attr(), which helps to get or set the attribute of an element. It can also tell if a particular attribute is present on an element or not. Instead of returning a Boolean expression, it returns the name of the matched attribute. If the attribute is not found then it will return 'undefined' as a result.

Syntax:

$('selector').attr('attribute-name');

While setting an attribute to an element, you can either directly set it by defining it or even by declaring a function for it. The function is an optional parameter over here. It can be used according to the need and requirements.

Let's check if an element contains the 'name' attribute with the following example.

Example for 'hasAttr checking to see if there is an attribute on an element'

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Check if there is an attribute on an element using jQuery</h2>
    <p id="myPara" name="para" value="one">This is a Paragraph tag.</p>
    <div id="myDiv" name="div" value="two">This is a div tag.</div>
    <p>Click the button to get check whether the paragraph tag contains 'name' or not. If yes, then it will return the 'name'.</p>
    <button id="button1">Check</button>
  </body>
  
<script type="text/javascript">
  $(document).ready(function(){
      $('#button1').on('click',function(){
          alert($('#myPara').attr('name'));
      })
  });
</script>
</html>

Output:

Example: hasAttr checking to see if there is an attribute on an element





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.