What is the best way to create the following div element in jQuery?
<div class="btn-group">
<button class="btn dropdown-toggle" title="Manage" data-toggle="dropdown">
<span class="caret"></span>
</button>
</div>
I've tried multiple formats, but I can't seem to get it right.
var itemsButtonsDiv = $('<div><button><span></span></button></div>')
.addClass("btn-group")
.attr({
title: "Manage",
"data-toggle": "dropdown"
})
.find("button")
.addClass("btn dropdown-toggle")
.find("span")
.addClass("caret")
;
var itemsButtonsDiv = $("<div><button><span></span></button></div>", {
"class": "btn-group",
html: " ?? Does everything else go here as one long text string ?? "
});
I realize that I have to append the element separately after I create it, but I can't get the creation right.
If I may suggest a traditional approach, I'd do something like this:
var group = document.createElement("div");
group.className = "btn-group";
var btn = document.createElement("button");
btn.className = "btn dropdown-toggle";
btn.title = "Manage";
btn.setAttribute("data-toggle","dropdown");
var caret = document.createElement("span");
caret.className = "caret";
btn.appendChild(caret);
group.appendChild(btn);
If you want to make a jQuery element out of the dom element, you can do $(group)
.
I believe that this traditional approach has several advantages:
If you find that too long, and more generally - this sort of code should be extracted to a method
function buildButtonGroup(){
// rest of the code here
return group;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With