Select all the first elements with a specific attribute value

advertisements

On a form, I have to select all first <a> elements with a specific attribute value from all the list items present in the form. For instance, in the below code, I have to select <a> elements with the content xxx and zzz — or in other words, the first <a> element with data-role="modal" from all list items.

console.log($('ul li a[data-role="modal"]:first'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a data-role="modal">xxx</a>
    <a data-role="modal">yyy</a>
  </li>
  <li>
    <a>abc</a>
    <a data-role="modal">zzz</a>
    <a data-role="modal">xyz</a>
  </li>
</ul>

The jQuery I tried is only selecting the one with xxx.


You can use .find() to get all a elements with attribute data-role=modal in ul li and apply :eq to get first for each match:

$('ul li').find('a[data-role="modal"]:eq(0)').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a data-role="modal">xxx</a>
    <a data-role="modal">yyy</a>
  </li>
  <li>
    <a>abc</a>
    <a data-role="modal">zzz</a>
    <a data-role="modal">xyz</a>
  </li>
</ul>

References

.find()

:eq