12.4. Writing Elements Dynamically

jQuery allows you to easily insert elements on a page. The following code appends a <p> tag to the <div> with an id of div1:

<script>$("<p>hello I am dynamically added text</p>").appendTo("#div1")</script>

You can also insert an element after the target element with the .insertAfter() method:

<script>$("<p>hello I am dynamic text</p>").insertAfter("body")</script>

Remember that adding elements dynamically works slightly differently in IE than in Firefox. While researching this chapter, I was playing around with the following script:

<script>$("<p>hello I am dynamic text</p>").appendTo("body")</script>

This works fine in Firefox but will give you a strange error when run in IE 7 (see Figure 12-3). Can you guess why?

Figure 12.3. Internet Explorer error

Why does this work fine in Firefox and not IE? Well, it is quite simple really; the problem is that the document was not fully rendered yet, so the script couldn't find the element when it ran. This is a common problem with JavaScript. So, how can you specify that a script should run only when the document is fully loaded?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.248.44