sarah.ferguson sarah.ferguson - 1 year ago 69
jQuery Question

jquery .attr() after .append()

I'm generating a select option programatically however the

.attr()
function after an
.append()
doesn't add the attribute to the just appended element but to the father.

Shouldn't
.append()
return the just appended element?

Here a JSFiddle example https://jsfiddle.net/cq24uv1x/1/

$("body").html($("<select>").append("<option>").attr('value',"bla bla bla").append("</option>").append("</select>"));


instead of getting a

<select><option value="bla bla bla"></option></select>


I get a

<select value="bla bla bla"><option></option></select>

Answer Source

Try this out:- https://jsfiddle.net/adiioo7/cq24uv1x/2/

JS:-

$("body").append($("<select>").append($("<option>").attr('value',"bla bla bla")));