javascripthtmljqueryjquery-selectors

Contains to return multiple values


I am using $('label:contains('something'); to get the label that contains 'something' in it it works perfectly fine but I want to be able to handle more than one label how to do it example:

HTML:

<html>    
<label for='michel'>My Name is Michel</label>
    <label for='allen'>My Name is Allen</label>
    <label for='chris'>His Name is Chris</label>
</html>

jQuery:

<script>    
label = $('label:contains(My Name is)');
    console.log(label.attr('for'));
</script>

now the console logs only michel I want to be able to handle more than one value, I want to log michel and allen


Solution

  • You could use jQuerys each function to iterate over all the labels.

    let labels = $('label:contains(My Name is)');
    
    labels.each(function(){
      console.log($(this).attr('for'));
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label for='michel'>My Name is Michel</label>
    <label for='allen'>My Name is Allen</label>
    <label for='chris'>His Name is Chris</label>