Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is proper way to create complex elements?

Tags:

jquery

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.

like image 355
Simpler Avatar asked Sep 01 '13 01:09

Simpler


1 Answers

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:

  • It's very straightforward what's happening, even if you're not 100% familiar with the jQuery API.
  • It's native, so it's likely faster since it doesn't have to invoke any parser.
  • Every element is defined first, and the relationships are defined later, so I think it's clearer.

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;
}
like image 88
Benjamin Gruenbaum Avatar answered Oct 08 '22 13:10

Benjamin Gruenbaum