bunnycode bunnycode - 1 month ago 11
jQuery Question

Getting #[object Object] when trying to get for attr for href

I have a dynamically generated

ol li
list, and each
li
has a
label
with a
for
attribute.

Like this:

<ol id="altErrorCont" class="error-container">
<li>
<label class="error" for="dobMonth">Enter the month you were born</label>
</li>
<li>
<label class="error" for="dobDay">Enter the day you were born</label>


On page load I want to wrap the labels with an
a
tag that contains an anchor for the
for
tag inside the label it wraps. This is what I want to happen:

<ol id="altErrorCont" class="error-container">
<li>
<a href="#dobMonth">
<label class="error" for="dobMonth">Enter the month you were born</label>
</a>
</li>
<li>
<a href="#dobDay">
<label class="error" for="dobDay">Enter the day you were born</label>
</a>


I wrote this, but it's not working:

var labelFor = $("ol#altErrorCont li label").each(function(){
$(this).attr("for");
});

$('ol#altErrorCont li > label').wrap('<a href="#'+ labelFor +'">');


It's returning
<a href="#[object Object]">
for each wrapped label. Can someone point me in the right direction or explain why this is happening?

Thanks in advance.

Answer

jQuery's .each() method returns jQuery object. When you use it in the string contcatenation, JavaScript calls toString() method on it. Since jQuery doesn't have its own toString method defined, it calls the method defined on the Object.prototype which returns [object Object].

Here is how I would go about it:

var labelFor = $("ol#altErrorCont li label").each(function(){
    $(this).wrap('<a href="#'+ $(this).attr("for") +'">');
});