Question:
Instead of doing:
var html = '<a href="' + data.href + '" title="' + data.title + '">' + data.desc + '</a>';
I'm doing:
var html = '<a href="{href}" title="{title}">{desc}</a>';
html = html
.replace( '{href}', data.href )
.replace( '{title}', data.title )
.replace( '{desc}', data.desc );
Or replace( /{nome}/g, data.nome )
if there are multiple occurrences.
Is there any "official" way or everyone has to solve it on their own by creating a custom function?
I found a couple of old plugins for jQuery, 2007 and 2008 . Has anything changed since then? Do JavaScript frameworks like jQuery or Mootools already incorporate this? If yes, what is the JS behind this?
Answer:
With jQuery you can use its element builder:
var $elemento = $("<a>", {href: data.href, title: data.title}).text(data.desc);
$('.umContainerParaNossoElemento').html($elemento);
console.log("Versão string: " + $elemento[0].outterHTML);
So you can build jQuery elements, which contain an HTMLElement. With this you can manipulate the element such as registering events, inserting other elements, etc, even before the object is in the document.
As asked, the first element you pass in the string of the tag(s) you want to create as < div>
or < ul>< li>
.
The second argument is an object with the tag attribute values, in camel case (HTML is case insensitive!), like {href: 'valor', class: 'umaClasse', type: 'button'}
.
Creating elements with jQuery – jQuery API