Easy jQuery - Text/HTML Methods
EasyProgramming.net tutorial showing how to use the various HTML/Text Methods available to you
by Nazmus Nasir
HTML
<!-- Easy jQuery - Reading and Writing to HTML Elements - #2 -->
<p>
Welcome to the second Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We'll learn how to read from and write to elements on your webpage. It's pretty simple!
</p>
<p>
We've already done this in vanilla JavaScript with innerHTML, innerText, and appending using +=. jQuery is very similar with a special methods to append or prepend.
</p>
<p>
jQuery Methods:
</p>
<table>
<thead>
<th>Method</th>
<th>Desc</th>
</thead>
<tbody>
<tr>
<td>$(selector).text()</td>
<td>Read the inner text of the element if no parameters are passed. Ovverride inner text if passed with parameter. </td>
</tr>
<tr>
<td>$(selector).html()</td>
<td>Read the inner HTML of the element if no parameters are passed. Ovverride inner HTML if passed with parameter.</td>
</tr>
<tr>
<td>$(selector).append("some text")</td>
<td>Add text/HTML after the selector</td>
</tr>
<tr>
<td>$(selector).prepend("some text")</td>
<td>Add text/HTML before the selector</td>
</tr>
<tr>
<td>$(selector).appendTo("some text")</td>
<td>Add text/HTML inside the selector as the very first element</td>
</tr>
<tr>
<td>$(selector).prependTo("some text")</td>
<td>Add text/HTML inside the selector as the very last element</td>
</tr>
<tr>
<td>$(selector).remove()</td>
<td>Remove the selected HTML element</td>
</tr>
</tbody>
</table>
<!-- Practice area -->
<h2>
Let's practice:
</h2>
<div id="text0">
This is some text from the first div
</div>
<div id="text1">
This is some text
</div>
<div id="text2">
This is some text
</div>
<ol id="shoppingList">
<li>Milk</li>
</ol>
<br />
<br />
<br />
<br />
<br />
CSS
td, th {
padding: 10px;
border-bottom: solid #000 1px;
font-size: .75em;
}
JavaScript
console.log($('#text0').text());
$('#text0').text('<strong>Now I\'m a different text</strong>');
$('#text1').html('<strong>Now I\'m a different text</strong>');
$('#text2').prepend('This text comes before -- ');
$('#text2').append(' -- This text comes after ');
$('#shoppingList').append('<li>Eggs</li>').append('<li>Cookies</li>').prepend('<li>Chocolate</li>');
$('#shoppingList li:nth-child(2)').remove();