Reputation: 29
I'm trying to create an element with an element inside of it in JQuery, but I'm not getting anything when I try and output it.
This is the HTML equivalent of what I'm looking for:
HTML:
<div class="btn-icn">
<button class="btn">
<span class="glyphicon glyphicon-comment"></span>
</button>
</div>
Jquery:
a = $(button).attr({
class: "btn";
id:"btn";
}.append($(icon).attr({
class:"glyphicon glyphicon-comment";
id="comment";
}));
alert(a);
Upvotes: 0
Views: 58
Reputation: 206593
$("<button/>", { // here goes the properties:
appendTo : ".btn-icn",
class : "btn",
id : "btn",
on : {
click : function(){ alert(this.tagName); }
},
append : $("<span/>", {
class : "glyphicon glyphicon-comment",
id : "comment"
})
});
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-icn"></div>
(Be aware that using an ID multiple times on a single page is wrong. Stick with classes instead.)
Upvotes: 1
Reputation: 9105
The jquery code is totally broken to me:
var a = $('<a />').attr({
class: "btn", //comma not semicol
id:"btn"
});
var icon = $('<i></i>').attr({
class: "glyphicon glyphicon-comment",
id: "comment" //no equal sign in an object, property: value
});
a.append(icon)
Upvotes: 0