For people who like to mess with what’s on a page

Sometimes you need to get the text of an element, or add some text to an element. ChocolateChip provides a versatile set of tools for doing this. Here are the methods:

  1. Element.text()
  2. Element.fill()
  3. Element.empty()
  4. Element.innerText
  5. Element.outerText
  6. Element.textContent
  7. String.trim()
  8. String.capitalize()
  9. String.capitalizeAll()
  10. $.concat()

Element.text()

The $.text() method can serve you in two ways: it can get the text of the element if no value is passed as an argument. If a string of text is passed as an argument, $.text() will fill the element with that text. When $.text() gets text, it preserves the white space between nodes. If you really want to collapse the text and eliminate any white space, use the textContent property described below. Here are some examples of $.text() in action:

<section>
	<p>The first paragraph is always the best.</p>
	<p>Sometmes the second is good enough.</p>
	<p>But does anyone ever pay attention to the third paragraph?</p>
	<ul>
		<li>Butterflies</li>
		<li>Godzilla</li>
		<li>Care Bears</li>
		<li>Rattlesnakes</li>
		<li>Unicorns</li>
	</ul>
</section>
$(function() {
    // Will return "The first paragraph is always the best"
    console.log($("p:first-of-type).text());
    // Will change the contents of the third paragraph.
    $("p:nth-of-type(3).text("The third paragraph is different now.");
    // Get the text of the fourth list item.
    var listItem = $("li:nth-of-type(4)").text();
    // Change the fourth list item to "Anacondas"
    $("li:nth-of-type(4).text("Anacondas");
    console.log("The fourth list item was: " + listItem + ", but now it is: " + $("li:nth-of-type(4)").text());
});

Element.empty()

This method empties and element of all its child nodes.

$(function() {
    $("#response").empty();
});

Element.innerText

This method returns the text of the element with white space formatting. A single spece separates inline elements and a new line separates block elements.

<table>
	<tr>
		<td>Row One Item One</td>
		<td>Row One Item Two</td>
	</tr>
	<tr>
		<td>Row Two Item One</td>
		<td>Row Two Item Two</td>
	</tr>
</table>

$(function() {
    console.log($("table").innerText);
});

The above code would output the following to the console:

Row One Item One	Row One Item Two
Row Two Item One	Row Two Item Two

When using innerText to set the content of an element, be aware that it does not parse the string for HTML elements. Any HTML markup in the string is output as text. This is great if you want to prevent malicious script injection in your app.

Element.outerText

Like innerText, outerText returns the text of the target element’s parent node, which would include the text of any other child nodes that the parent has. Similarly, if you assign a text value to the element’s parent using outerText, all of the parent’s child nodes will be replaced with the new text. This is the same as the behavior of outerHTML.

Element.textContent

In contrast to innerText, textContent returns all of the whitespace, as if the content were in a set of pre tags.

$(function() {
    console.log($("table").textContent);
});

The above code would output the following to the console:

			Row One Item One
			Row One Item Two
		
		
			Row Two Item One
			Row Two Item Two

As you can see in the above example, textContent returned even the white space of the table row indentation. When using textContent to set the content of an element, anyy HTML markup in the string is output as text. This is different from what innerHTML does. This is great if you want to prevent malicious script injection in your app. Here’s an example of how textContent handles markup passed in as a string:

$(function() {
    var text = "<a href='#' onclick='doEvilThings()'>Please click here</a>";
    $("p:first-of-type").textContent = text;
});

This gets output as:

<a href='#' onclick='doEvilThings()'>Please click here</a>

Instead of something like this: Please click here

As you can see, the malicious code has been rendered as plain text. Life is good when the bad guys lose.

String.trim()

This method removes any white space at the beginning and end of a string.

<ul>
		<li>item 1</li>
		<li>item 2</li>
		<li>item 3</li>
		<li>item 4</li>
		<li>     item 5     </li>
	</ul>
$(function() {
    // Will return: "item 5" with no white space.
    var text = $("p:last-of-type").text().trim();
});

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has two new methods for capitalizing strings: String.capitalize() and String.capitalizeAll(). String.caplitalize() capitalizes the first letter of the string, regardless of whether it has multiple words. String.capiatlizeAll() capitalizes the first letter of every word in the string. Here how you use them:

var sstr = "this is a string";
console.log(sstr.capitalize()); // => This is a string
console.log(sstr.capitalizeAll()); // => This Is A String

As of version 1.3.0, the following method is available:

$.concat()

In general, string concatenation is not very performant in JavaScript. However, using the Array.join method creates a string from an array very efficiently. $.concat() uses arrays or array like objects to perform efficient string concatenation. You pass an array of strings as the argument.
If you have an array-like object, you can convert it to an array using $.slice() (see example below).

var users = ["<li>Item One</li>","<li>Item Two</li>","<li>Item Three</li>","<li>Item Four</li>","<li>Item Five</li>"];
users.prependTo("#users > ol");
// Get the arguments object to prepend:
function outputString(){
    var str = $.slice(arguments);
    str.prepend("#message");
}
outputString("This"," ","is"," ","a"," ","tedious"," ","example",".");
Advertisements