Posted by dwahlin at Dan Wahlin’s WebLog
Previous Tips:
- jQuery Tip #1 – Defining a Context When Using Selectors
- jQuery Tip #2 – Manipulating the DOM in a Loop
- jQuery Tip #3 – Using the data() Function
- jQuery Tip #4 – Use the on() Function for Event Handling
jQuery’s selector functionality makes it easy to add new nodes into the DOM without making a lot of calls to document.createElement(). For example, the following code adds
$('').appendTo('#divContainer');
The first part of the code (before appendTo()) creates an initial set and adds it to the stack. Once the set is on the stack you can go into it and use find() to grab specific nodes and then modify them as show next:
$('') .find('span') .html(custName) //Update with some dynamic variable .appendTo('#divContainer');
In cases where you need to dynamically generate DOM nodes, modify specific children as with the shown above, and then append the newly created set into a container, what do you do? Fortunately, jQuery provides an end() function that allows you to pop the current set off the stack and then move down to the next one. In the example above, calling end() immediately before appendTo() would cause the initial
If you’re interested in learning more about jQuery or JavaScript check out my jQuery Fundamentals or Structuring JavaScript Code courses from Pluralsight. We also offer onsite/online training options for companies as well at www.thewahlingroup.com. While there are certainly other ways to accomplish this type of functionality, end() can be handy to know about when you need to chain several functions together and move around in the stack.
Once find() is invoked you’re on the node so it will be appended to divContainer instead of the
$(document).ready(function () {
var custs = getCustomerData();
for (var i = 0; i < custs.length; i++) {
var cust = custs[i];
$('
The code starts by creating the
Live Example
Conclusion
