Search code examples
jqueryattributes

Checking if button has a specific attribute does not work in jQuery


I have this code:

<body>
  <button class="test" aria-label="This is a button">
    <span>test</span>
  </button>

  <button class="test2" aria-label="This is a second button">
    <span>test2</span>
  </button>
</body>
jQuery(document).ready(function($) {
 if( $("button").attr("aria-label") ) {
     $(this).find("span").attr("aria-hidden", "true");
  }
});

I want to add aria-hidden to true to all span elements if it's parent (button) has attribute aria-label.

I tried chaning my code to something like this:

jQuery(document).ready(function($) {
 if( $("button").attr("aria-label") ) {
     $("span", this).attr("aria-hidden", "true");
  }
});

AND

jQuery(document).ready(function($) {
 if( $("button").getAttribute("aria-label") ) {
     $("span", this).attr("aria-hidden", "true");
  }
});

but it's not working.


Solution

  • You can achieve using has function to check for particular attribute in the element as follows:

    $(document).ready(function() {
        if($("button").has("aria-label")) {
            $(this).find("span").attr("aria-hidden", "true");
        }
    });
    

    To achieve above functionality with all buttons as follows:

    $(document).ready(function() {
        $('button.test').each(function() {
            if($(this).attr("aria-label")) {
                $(this).find("span").attr("aria-hidden", "true");
            } else {
                alert('Something wrong');
            } 
        });
    });
    <!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">
        <title>Document</title>
    </head>
    
    <body>
    
    <div>
            <h1>Test this Task</h1>
            <button class="test" aria-label="This is a button">
                <span>test</span>
              </button>
            
              <button class="test" aria-label="This is a second button">
                <span>test2</span>
              </button>
        </div>
    
    
        <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
    </body>
    
    </html>