Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

Using the DOM API of JavaScript

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

Using the DOM API of JavaScript

Post by admin » Sat Oct 19, 2019 4:41 pm

Using the DOM API
DOM stands for Document Object Model. It is an object-oriented representation of structured documents like XML
and HTML.
Setting the textContent property of an Element is one way to output text on a web page.
For example, consider the following HTML tag:

Code: Select all

<p id="paragraph"></p>
To change its textContent property, we can run the following JavaScript:

Code: Select all

document.getElementById("paragraph").textContent = "Hello, World";
This will select the element that with the id paragraph and set its text content to "Hello, World":

Code: Select all

<p id="paragraph">Hello, World</p>
(See also this demo) - http://jsbin.com/fuzijox/edit?html,js,console,output
You can also use JavaScript to create a new HTML element programmatically. For example, consider an HTML
document with the following body:

Code: Select all

<body>
<h1>Adding an element</h1>
</body>
In our JavaScript, we create a new <p> tag with a textContent property of and add it at the end of the html body:

Code: Select all

var element = document.createElement('p');
element.textContent = "Hello, World";
document.body.appendChild(element); //add the newly created element to the DOM
That will change your HTML body to the following:

Code: Select all

<body>
<h1>Adding an element</h1>
<p>Hello, World</p>
</body>
Note that in order to manipulate elements in the DOM using JavaScript, the JavaScript code must be run after the relevant element has been created in the document. This can be achieved by putting the JavaScript <script> tags after all of your other <body> content. Alternatively, you can also use an event listener to listen to eg. window 's onload event, adding your code to that event listener will delay running your code until after the whole content on your page has been loaded.

A third way to make sure all your DOM has been loaded, is to wrap the DOM manipulation code with a timeout
function of 0 ms - https://stackoverflow.com/questions/779 ... mes-useful . This way, this JavaScript code is re-queued at the end of the execution queue, which gives the
browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript.

Post Reply