15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

76 <strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

insertAdjacentHTML(“location”, “HTMLtext”)<br />

insertAdjacentText(“location”, “text”)<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 these<br />

two methods. The example here demonstrates the result of employing both methods<br />

in an attempt to add some HTML to the beginning of the myP element.<br />

Begin by assigning a string of HTML code to the global variable a:<br />

a = “Important News!”<br />

Because this HTML is to go on the same line as the start of the myP paragraph, use<br />

the afterBegin parameter for the insert method:<br />

myP.insertAdjacentHTML(“afterBegin”, a)<br />

Notice that there is no space after the exclamation mark of the inserted HTML.<br />

But to prove that the inserted HTML is genuinely part of the document’s object<br />

model, you can now insert the text of a space after the B element whose ID is myB:<br />

myB.insertAdjacentText(“afterEnd”, “ “)<br />

Each time you evaluate the preceding statement (by repeatedly clicking the<br />

Evaluate button or pressing Enter with the cursor in the topmost field), an additional<br />

space is added.<br />

You should also see what happens when the string to be inserted with<br />

insertAdjacentText() contains HTML tags. Reload The Evaluator and enter the<br />

following two statements into the topmost field, evaluating each one in turn:<br />

a = “Important News!”<br />

myP.insertAdjacentText(“afterBegin”, a)<br />

The HTML is not interpreted but is displayed as plain text. There is no object<br />

named myB after executing this latest insert method.<br />

insertBefore(newChildNodeObject[,<br />

referenceChildNode])<br />

elementObject.insertBefore()<br />

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

Compatibility ✓ ✓ ✓

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

Saved successfully!

Ooh no, something went wrong!