Get element by attribute in jQuery

You can get element based on attribute. As you know we use ('#id') for id and ('.class') for class to select elements. Same as if you want to get element by attribute then you have to use ('[attribute]').

You have to pass the attribute name in ('[]') with or without value. If you pass the attribute with value then it will select only element which attribute have equal to passed value. If you pass attribute name without value then it select all element which have passed attribute.

$('li[cid]').css('background', 'Yellow');
// Select all li which have 'cid' attribute

$('li[cid="1"]').css('background', 'Green');
// Select all li which have 'cid' attribute and cid value equal to 1

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnCountry').click(function () {
        $('li[cid]').css('background', 'Yellow');
      });

      $('.btnIndia').click(function () {
        $('li[cid="1"]').css('background', 'Green');
      });

    });
  </script>
</head>
<body>
  <div class="Container">
    <ul>
      <li>Country List</li>
      <li cid="1">India</li>
      <li cid="2">Pakistan</li>
      <li cid="3">Japan</li>
    </ul>
    <button type="button" class="btnCountry">Select Country</button><br />
    <button type="button" class="btnIndia">Select India</button><br />
    Please click the above button to test the code.
  </div>
</body>
</html>
DISPLAY
  • Country List
  • India
  • Pakistan
  • Japan


Please click the above button to test the code.

No comments :

Please Give Your Feedback