What is the best way to create elements? [duplicate]

5
for(var i=0; i< numTotalPerguntasDig; i++){

strInterface +=

            "<ul>"+
            "<li class=\"col-md-2 \">"+
            "   <button type=\"button\" class=\"btn btn-danger btn-info-bloco form-control\">"+
            "       <span class=\"glyphicon glyphicon-plus-sign\" aria-hidden=\"true\"></span>" +
            "       <span class=\"texto-btn\">/span>"+
            "   </button>"+
            "</li>"+*/
            "<li class=\"col-md-2 \">"+"<input type='text' class='info-1 form-control' style='width: 100%' value='"+arraySeq[i]+"'/>"+"</li>"+
            "<li class=\"col-md-6 \">"+"<input type='text' class='info-2 form-control'  placeholder='Digite'/>"+"</li>"+
            "<li class=\"col-md-2 \">"+
            "   <select class='info-3 form-control'>"+
            "       <option value='1'>1</option>"+
            "   </select>"+
            "</li>"+
            "<li class=\"col-md-2\">"+
                "<button class='btnadd btn btn-danger btn-sm form-control' value='x'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span> </button>"+
            "</li>"+
            "</ul>";


menu.append(strInterface);

}

append or createElement ?

What is the best way or the most visual way to understand the code in future maintenance?

    
asked by anonymous 17.08.2015 / 13:57

5 answers

4

As I said, it's best not to use string concatenation, here's an example with Handlebars (Template Engine).

Note that you can add loops and conditions within your template. another important point to note is that the <script type="text/template"></script> element is ignored by the browser at the time of rendering, so it will only be used by the script (no impact on the initial loading of the page).

The two major advantages of this approach are to leave the script clean, just as the content of the template is much closer to the final HTML, without escape characters ("\") or concatenations ("+ + variable") .

var model = {
  perguntas: ["Banana", "Maça", "Pera"]
};

var menu = $("#menu");
var source  = $("#tmlMenu").html();
var tmlMenu = Handlebars.compile(source);
var menus = $.parseHTML(tmlMenu(model));

menu.append(menus);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js"></script><divid="menu">

</div>

<script id="tmlMenu" type="text/template">
  {{#each perguntas}}
  <ul>
    <li class="col-md-2 ">
      <button type="button" class="btn btn-danger btn-info-bloco form-control">
        <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
        <span class="texto-btn"></span>
      </button>
    </li>
    <li class="col-md-2 "><input type='text' class='info-1 form-control' style='width: 100%' value='{{this}}'/></li>
    <li class="col-md-6 "><input type='text' class='info-2 form-control'  placeholder='Digite'/></li>
    <li class="col-md-2 ">
      <select class='info-3 form-control'>
        <option value='1'>1</option>
      </select>
    </li>
    <li class="col-md-2">
      <button class='btnadd btn btn-danger btn-sm form-control' value='x'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>
    </li>
  </ul>
  {{/each}}
</script>
    
17.08.2015 / 14:23
6
Using jQuery is possible to create an element in a way that I particularly consider more elegant, however each element needs to be created individually.

div = $("<div>", {
  "class" : "novo_elemento segunda_classe",
  id : "elemento_teste",
  height : "150px",
  width : "200px"
});

$("body").html(div);
#elemento_teste{
    border: solid 1px red;
}

.novo_elemento{
    background: black;
    height: 100px;
    width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Withthismethodyoucanaddthiscreatedelementusing.append(),.prepend(),.appendTo(),.prependTo()and.html().

Soyougettohaveanelegantstatementofyourelementandyoucanapplyitinanywayyoufeelismostappropriate.

A"negative" point of creating an element of this form is the need to create each element individually, which makes the initial creation harder, but this is also a good point as it also gives you greater control over each one and makes it possible to reuse them, thus facilitating the maintenance of your code.

Just as an example of how this can help you to leave your code with better maintenance you can for example create models of elements and from there modify only their peculiarities

Example:

inputDefault = $("<input>",{
    "class" : "input",
    name : "Input",
    type : "text"
});

inputAge = inputDefault.clone().attr({
    name : "age"+inputDefault.attr("name"),
    type : "number",
    placeholder: "Idade"
});

inputName = inputDefault.clone().attr({
    name : "name"+inputDefault.attr("name"),
    placeholder: "Nome"
});

$(".inputs").html(inputName)
	.append("<br>")
	.append(inputAge);
.inputs{
    background: #f0f0a0;
    border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="inputs"></div>
    
17.08.2015 / 14:16
2

With jQuery you can create the element to define its attributes dynamically as follows:

$('<button/>', {
    class: 'btn btn-danger btn-info-bloco form-control',
    name: 'btn-login',
    text: 'Login'
}).appendTo('#form');

Practical and visually elegant.

    
17.08.2015 / 14:10
2

Another way is to use the script tag with a type different.

Example:

$(function()
{
   $('#container').append($('#tpl').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scripttype="text/template" id="tpl">
      <div class="x">
        <p class='y'>Olá mundo</p>
  </div>
</script>

<div id="container"></div>

This happens because content within script with type text/template is not interpreted as javascript!

    
17.08.2015 / 14:44
1

One option is to use ready-made text, append to the DOM, and then change only what you need. Assuming jQuery:

var item = "<li class=\"col-md-2 \">"+
            "   <button type=\"button\" class=\"btn btn-danger btn-info-bloco form-control\">"+
            "       <span class=\"glyphicon glyphicon-plus-sign\" aria-hidden=\"true\"></span>" +
            "       <span class=\"texto-btn\">/span>"+
            "   </button>"+
            "</li>"+*/
            "<li class=\"col-md-2 \">"+"<input type='text' class='info-1 form-control' style='width: 100%' value=''/>"+"</li>"+
            "<li class=\"col-md-6 \">"+"<input type='text' class='info-2 form-control'  placeholder='Digite'/>"+"</li>"+
            "<li class=\"col-md-2 \">"+
            "   <select class='info-3 form-control'>"+
            "       <option value='1'>1</option>"+
            "   </select>"+
            "</li>"+
            "<li class=\"col-md-2\">"+
                "<button class='btnadd btn btn-danger btn-sm form-control' value='x'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span> </button>"+
            "</li>";

for(var i=0; i< numTotalPerguntasDig; i++){
    var elemento = $(item);
    elemento.find(".info-1.form-control").val(arraySeq[i]);
    menu.append(elemento);
}

So the structure of the HTML to be inserted is obvious, and concatenation is only done once. The variable part actually occurs directly in the DOM (i.e. should be very efficient).

    
17.08.2015 / 16:10