skip to Main Content

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

2

Answers


  1. 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>
    Login or Signup to reply.
  2. $('label:contains(My Name is)'); return the selected document object that matches the give parameters. In your case there are two elements are being selected

    /**id:1**/
      "0": <label for="michel">My Name is Michel</label>,
      "1": <label for="allen">My Name is Allen</label>,
      "length": 2,
    

    To access the each of the item from the selected object you need to loop through it. See the following example.

    var $label = $('label:contains(My Name is)');
    
    $.each($label, function(i, val) {
      console.log($(val).attr('for'));
    });
    
    // Check the type of your data
    console.log(typeof($label));
    
    // See the selected object
    console.log($label);
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search