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

Time:12-12

I have this code:

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

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

CodePudding user response:

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  aria-label="This is a button">
            <span>test</span>
          </button>
        
          <button  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>

  • Related