15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5 ✦ Body Text Objects (Chapter 19)<br />

To inspect the object returned by the parentElement() method, enter the following<br />

statement in the lower text box:<br />

a.parentElement()<br />

If you scroll down to the outerHTML property, you see that the parent of the text<br />

range is the myEM element, tag and all.<br />

Next, extend the end point of the text range by one word:<br />

a.moveEnd(“word”)<br />

Because part of the text range now contains text of the myP object, the outerHTML<br />

property of a.parentElement() shows the entire myP element and tags.<br />

pasteHTML(“HTMLText”)<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓ ✓<br />

Example<br />

Use The Evaluator (Chapter 13 in the <strong>JavaScript</strong> <strong>Bible</strong>) to experiment with the<br />

pasteHTML() method. The goal of the following sequence is to change the tag<br />

to a tag whose STYLE attribute sets the color of the original text that was in<br />

the EM element.<br />

Begin by creating the text range and setting the boundaries to the myEM element:<br />

a = document.body.createTextRange()<br />

a.moveToElementText(myEM)<br />

While you can pass the HTML string directly as a parameter to pasteHTML(), storing<br />

the HTML string in its own temporary variable may be more convenient (and<br />

more easily testable), such as:<br />

b = “” + a.text + “”<br />

Notice that we concatenate the text of the current text range, because it has not<br />

yet been modified. Now we can paste the new HTML string into the current text<br />

range<br />

a.pasteHTML(b)<br />

At this point the EM element is gone from the object model, and the SPAN element<br />

is in its place. Prove it to yourself by looking at the HTML for the myP element:<br />

myP.innerHTML<br />

As noted earlier, the pasteHTML() method is not the only way to insert or<br />

replace HTML in a document. This method makes excellent sense when the<br />

user selects some text in the document to be replaced, because you can use the<br />

document.selection.createRange() method to get the text range for the selection.<br />

But if you’re not using text ranges for other related operations, consider the<br />

other generic object properties and methods available to you.<br />

313<br />

TextRange.pasteHTML()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!