Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jQuery - Manipulating

jQuery - Manipulating

Introduction to jQuery's text, html, append, prepend, and remove methods.

John Nunemaker

October 20, 2010
Tweet

More Decks by John Nunemaker

Other Decks in Programming

Transcript

  1. $('.article').each(function() { // what is diff between // this and

    $(this) here this; $(this); }); this is a plain DOM element, $(this) is a DOM element bestowed with the power of jQuery
  2. .text() http://docs.jquery.com/Attributes/text <div id="content"> <p>This is my <strong>paragraph</strong>.</p> </div> <script

    type="text/javascript"> $('#content').text(); // This is my paragraph </script> Removes all HTML tags and returns just plain text.
  3. .html() vs .text() <div id="content"> <p>This is my <strong>paragraph</strong>.</p> </div>

    <script type="text/javascript"> $('#content').html(); // <p>This is my <strong>paragraph</strong>.</p> $('#content').text(); // This is my paragraph </script>
  4. .text(val) http://docs.jquery.com/Attributes/text#val <div id="content"> <p>This is my <strong>paragraph</strong>.</p> </div> <script

    type="text/javascript"> $('#content').text('This is my paragraph.'); </script> <div id="content"> This is my paragraph. </div> Sets the plain text of the element. Escapes any HTML.
  5. .html(val) vs .text(val) <div id="content"> <p>This is my paragraph.</p> </div>

    <script type="text/javascript"> $('#content').html('<p>My paragraph.</p>'); $('#content').html(); // <p>My paragraph.</p> $('#content').text('<p>My paragraph.</p>'); $('#content').html(); // &lt;p&gt;My paragraph.&lt;/p&gt; </script> .text(val) escapes HTML entities like <, > and &.
  6. <ul id="todo-list"> <li>Prep for class</li> <li>Teach class</li> </ul> <script type="text/javascript">

    $('#todo-list').append('<li>Demo append to students</li>'); </script> <!-- list is now --> <ul id="todo-list"> <li>Prep for class</li> <li>Teach class</li> <li>Demo append to students</li> </ul> this was added
  7. .prepend best way to insert content inside of an element

    at the beginning http://docs.jquery.com/Manipulation/prepend
  8. <ul id="todo-list"> <li>Prep for class</li> <li>Teach class</li> </ul> <script type="text/javascript">

    $('#todo-list').prepend('<li>Wake up and drink coffee</li>'); </script> <!-- list is now --> <ul id="todo-list"> <li>Wake up and drink coffee</li> <li>Prep for class</li> <li>Teach class</li> </ul> this was added
  9. <ul id="todo-list"> <li id="todo-prep">Prep for class</li> <li id="todo-teach">Teach class</li> </ul>

    <script type="text/javascript"> $('#todo-prep').remove(); </script> <!-- list is now --> <ul id="todo-list"> <li id="todo-teach">Teach class</li> </ul> #todo-prep was removed