user244394
user244394

Reputation: 13488

Appending text/elements to a DIV tag

How do I add text/elements to a target element (div) using getElementById (without ) when the page loads?

Here's my markup currently:

<html>
<head>
<title>test</title>

<script language="javascript">


/document.getElementById('content').innerHTML = 'Fred Flinstone';

</script>
</head>

<body>

<div id="content">
dssdfs

</div>


</body>
</html>

Upvotes: 1

Views: 2266

Answers (3)

Mike Dinescu
Mike Dinescu

Reputation: 55760

The quickest (although not the best) way to do it is to put your script block towards the end of the HTML file (after the <div> you wish to modify).

The better way to do it is to register for DOM load notification

If you want it to execute after the page loads, then you need to observe the DOM loaded event. You can do that by subscribing to the DOM load event in the script block and then put the code that manipulates the DIV in the event handler.

The tricky part is that different browsers may need slightly different ways to register to be notified when the DOM is loaded (that's were jQuery or a different library becomes useful)

Here's some more information about different ways to register for a callback to be called when the DOM is loaded. The information may be a bit out of date as more modern versions of the popular browsers have become more standards compliant now: http://www.javascriptkit.com/dhtmltutors/domready.shtml

Upvotes: 0

MRR0GERS
MRR0GERS

Reputation: 654

<script type="text/javascript">
    function dothis()
    {
        document.getElementByID('content').innerHTML = 'Fred Flinstone';
    }
</script>

<body onLoad="dothis()">
    ...
</body>

Upvotes: 1

Matthew Vines
Matthew Vines

Reputation: 27581

I think what is happening is that your script is executing before your document is ready. Try placing your javascript in a body load event.

Upvotes: 0

Related Questions