vandelay vandelay - 1 month ago 11
HTML Question

Get the label text with jquery

I'm trying to get the text inside a label through jquery. But I've only managed to get the entire html input to show. Where I'd like to just get the text.

I generate a label with a checkbox in a loop as shown below:

for (var key in data['results']){

SearchResultsOutter = $('<div />', {
'class' : 'SearchResultsOutter',
}).appendTo('.searchresultswrapper');

paraCheck = $('<label />').html(data['results'][key])
.prepend($('<input/>').attr({ type: 'checkbox', 'class': 'SearchResultsSibling'}));

paraCheck.appendTo(SearchResultsOutter)
}


And once I click a button I'd like to get the text of the label, through this click event:

$('.searchresultcontrol1').on('click', function(){
console.log('Here');
outter = $('.searchresultswrapper');

var lst = [];

outter.children('div').each(function () {
if ($(this).find('input').is(":checked")){
lbl = $(this).find('label').html();
console.log(lbl);
}
});
});


But I've only managed to get the console to print out:

enter image description here

I have tried to use
val()
but it does not print out anything

I'd like to get just:

(CDI.L) Candover Investments plc, LSE (Asset Management)
(YVI.MI) Valore Italia Holding di Partecipazioni S.p.A., MIL (Asset Management)

Answer

As per my comment: use .text() instead of .html(). The difference between the two is that the former gets the combined text within the selector, while latter gets the HTML content.

In this case, you would want to use .text() so that you leave out the <input> child DOM node.