Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Overview of this book

Table of Contents (18 chapters)
Learning jQuery
Credits
About the Authors
About the Reviewers
Preface

Inserting New Elements


jQuery has two methods for inserting elements before other elements: .insertBefore() and .before(). These two methods have the same function; their difference lies only in how they are chained to other methods. Another two methods, .insertAfter() and .after(), bear the same relationship with each other, but as their names suggest, they insert elements after other elements. For the Back to top links we’ll use the .insertAfter() method:

$(document).ready(function() {
  $('<a href="#top">back to top</a>').insertAfter('div.chapter p');
  $('<a id="top"></a>');
});

The .after() method would accomplish the same thing as .insertAfter(), but with the selector expression preceding the method rather than following it. Using .after(), the first line inside $(document).ready() would look like this:

$('div.chapter p').after('<a href="#top">back to top</a>');

With .insertAfter(), we can continue acting on the created <a> element by chaining...