I have a button that grabs some data from the server using ajax, and when it's done, it it supposed to add a element to the DOM.
The element to add will be something like this
<div class="SomeClass">
<div class="SomeOtherClass">
<span class="Name">name from server</span>
<span class="Manufacturer">manufacturer from server</span>
</div>
<span class="Weight">weight from server</span>
</div>'
In my jQuery function that gets the data back from the server, what is the best way to create this structure, put the data (name, manufacturer and weight) from the server in at the correct places, and put it into the DOM. I have got it working like this:
$("#ItemList").append('<div class="SomeClass"><div class="SomeOtherClass"><span class="Name">' + value.name + '</span><span class="Manufacturer">' + value.manufacturer + '</span></div> ' +
'<span class="Weight">' + value.weight + '</span></div>');
But this does not look very good, and it's hard to see the proper structure.
What is the best way of doing this in a clean manner?
The jQuery append() method inserts content AT THE END of the selected HTML elements.
prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).
jQuery after() Method The after() method inserts specified content after the selected elements.
If i needed multiple "version" of the structure I would go with adding something like
<div class="SomeClass" id='SomeClassTemplate' style='display:none'>
<div class="SomeOtherClass">
<span class="Name">name from server</span>
<span class="Manufacturer">manufacturer from server</span>
</div>
<span class="Weight">weight from server</span>
</div>
at the bottom of my html body, and then inside my the event handler where the element is to be added i would do
var newDiv = $("#SomeClassTemplate").clone();
newDiv.attr("id","whatever")
// remember this id should be different for each instance. or you can remove it
.appendTo("whatever") // depends on where in DOM you want to insert it
.find(".name").html("My name");
newDiv.find('.manufacturer').html("my manufacturer);
newDiv.show();
The advantage i found with this approach is that this code can easily be modified by tweaking the selectors in case the structure changes.
If you want to keep readability in mind then the following approach is both clean and doesn't perform any unnecessary jQuery lookups to add the content.
var div = '<div class="someClass">' +
' <div class="SomeOtherClass">' +
' <span class="Name">' + value.name + '</span>' +
' <span class="Manufacturer">' + value.manufacturer + '</span>' +
' </div>' +
' <span class="Weight">' + value.weight + '</span>' +
'</div>';
$('#itemList').append(div);
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