Reputation: 482
How to make working the function to a prepended element? Sorry if the question sounds wrong. Now Im using this code:
function listOfProduct() {
$('.list-of-product li').prepend('<input type="checkbox" name="list-of-product"><label class="list-of-product-element"></label>');
$('.list-of-product li').each(function (i) {
i++ ;
$(this).prev('input').attr('id', 'list-of-product-' + i);
$(this).prop('for', 'list-of-product-' + i);
});
}
I add to <li>
these elements which are inside the prepend()
and after that I want dynamicaly add specific attributes. Now its not working. Can anyone explain me why?
Upvotes: 1
Views: 19
Reputation: 167182
I believe, in the second one, you need to use $('.list-of-product li label')
because, for
is for <label>
. And also, the label's previous is the <input />
.
Try this:
function listOfProduct() {
$('.list-of-product li').prepend('<input type="checkbox" name="list-of-product"><label class="list-of-product-element"></label>');
$('.list-of-product li label').each(function (i) {
i++ ;
$(this).prev('input').attr('id', 'list-of-product-' + i);
$(this).attr('for', 'list-of-product-' + i);
});
}
Upvotes: 1
Reputation: 171669
you can't have an <input>
as previous element to an <li>
...they are children of the <li>
try:
$('.list-of-product li').each(function (i) {
i++ ;
$(this).find('input').attr('id', 'list-of-product-' + i);
$(this).find('label').prop('for', 'list-of-product-' + i);
});
Upvotes: 1