1

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 2

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>

1
  • Note: if you want to collate them all use .map rather than push into an array using .each (this answer doesn't do that, just adding info).
    – fdomn-m
    Commented Dec 20, 2023 at 14:24
1

$('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>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.