Home » JavaScript Tutorial

Understanding DOM with JavaScript

In this article, we are going to learn about DOM with JavaScript, Manipulating DOM with JavaScript and HTML with JavaScript.
Attaching JS with HTML | Fetching from HTML using JavaScript | Changing texts in HTML using JS | Creating and deleting HTML elements via JS.
Submitted by Himanshu Bhatt, on September 19, 2018

Introduction:

What is the Document Object Model (DOM)? First, understand, Document is any file like a spreadsheet, word and in case of JavaScript HTML. In HTML we see different kind of tags, that defines body, head, title, buttons or forms, these are the objects and how we have structured defines the model.

Example:

DOM with JavaScript 1

See how the HTML documented is structured in a specific manner? Everything is under <html></html> and the head of this document has title, and the body of the HTML will be inside the <body> </body> (body tags) and this is its structure. In the upcoming sections, we will discuss How to manipulate HTML using JavaScript?

Linking JavaScript with HTML [Section 1]:

We created two files, one is index.html which will be our main HTML file and other myScript.js our script for all the demonstrations.

index.html

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
	</head>
	<body>
		<H1>This is my new file</H1>
		<script src="myScript.js"></script>
	</body>
</html>

Now, this is our index.html file look it has a tagging script where we called which link myScript.js with src source, the name of our script.

myScript.js

    alert("JavaScript is Loaded")

Tip: Keep both files under the same directory otherwise it will cause some problem later.

Result:

DOM with JavaScript 2

Now keeping index.html same we will make changes in JavaScript to understand.

Fetching data from HTML using JS [Section 2]:

To fetch any kind of data from HTML we will use document object.

Change in myScript.js

    console.log(document);

So this line will console log out the HTML document.

DOM with JavaScript 3

This will be at the console of your browser, see here the whole HTML document is showing.

We can access the specific tags too. Like somechanges, we made into our JavaScript file.

myScript.js

    console.log(document.head);
    console.log(document.body);

Now using the following format of "document.tags" we can access the specific tag.

Let's see an example:

DOM with JavaScript 4

We can even fetch URL of the document that we did next is fetched URL after changing myScript.js:

    console.log(document.URL);
DOM with JavaScript 5

We have two outputs since we console out two tags head and body. We can do several tags too, for more tags visit: MDN Document documentation

Now we will see one last example:

We can get the data from any tag like <p> or <H1>, let's see how it's done.

index.html

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
	</head>
	<body>
		<H1>This is my new file</H1>
		<p>This is first para</p>
		<p id='ID'>This is second para with an ID</p>
		<p class="classone">Third para with class</p>
		<script src="myScript.js"></script>
	</body>
</html>

myScript.js

    console.log(document.getElementById('ID'))
    console.log(document.getElementsByClassName('classone')[0]);
    console.log(document.querySelector('H1'));
    console.log(document.querySelectorAll('p'));

Console Screen:

DOM with JavaScript 6

We used getElementById to fetch any tag with its ID name and same in the second line but instead of ID, we used class name (we used [0] because class returns the whole class and we only need its first element). In the last two lines we used querySelector and querySelectorAll which can get any tag, querySelector will return the first tag in HTML that match while querySelectorAll will return all the tags.

Tip: Where to place the script in the HTML?

Well, it is a quite usual discussion over where we should add our script in HTML.

Some say, We should add it in the 'Head' of the HTML so when the page will load it will load the script too so it will perform well, while some argue that we should put it in the last in the body so the HTML page will load faster. Who's right?

Well both are right and both are wrong as well (*wink*) let me explain it with an example:

Now I will make changes to our index.html program, placing our script in the head tag.

index.html

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
		<script src="myScript.js"></script>
	</head>
	<body>
		<H1>This is my new file</H1>
		<p>This is first para</p>
		<p id='ID'>This is second para with an ID</p>
		<p class="classone">Third para with class</p>
	</body>
</html>

While the myScript.js is same as in the last example, now let's see the Console screen:

DOM with JavaScript 7

Do you notice, all the previous values changed to null or undefined. Why? Because we placed our script in the head and when the head was loaded and or script ran but that time the rest body was not there hence null or undefined, instead of this we had placed it at bottom of Body it will produce the right result as in the previous example.

So the position of the scriptis totally depending what our script's purpose is.

Changing the Texts in HTML using JS [Section 3]:

So far we have learned how to attach our JavaScript with our HTML later, how to fetch data from the HTML document using JavaScript. Now, in this section, we will learn how to change the texts in the HTML with JS.

Most of time our index.html will remain same.

index.html

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
	</head>
	<body>
		<H1>This is my new file</H1>
		<p>This is first para</p>
		<p id='ID'>This is second para with an ID</p>
		<p class="classone">Third para with class</p>
		<script src="myScript.js"></script>
	</body>
</html>

Now we will try to change the title of our webpage.

So our myScript.js

    alert('Title will change using JavaScript')
    document.title = 'IncludeHelp'

We put an alert so we can see the change (otherwise it will change it very fast). Our webpage will be:

DOM with JavaScript 8

Notice the title here, and on clicking "ok" we the title change to "IncludeHelp":

DOM with JavaScript 9

Now we have paragraphs and one heading here so can we change this too?

Let’s try changing it too. Now the thing to note down is, we cannot change the text content of any tag like title we did earlier but there is a slight change as these tags contain other attributes other than text.

myScript.js

    alert('Text in H1 will change using JavaScript')
    let element = document.querySelector('H1')
    element.textContent = 'Successfully changed'

We used "textContent" which is obvious, it will be the text of that tag and hence we changed it.

Let’s see the body of our webpage...

DOM with JavaScript 10

Now in next Example we will use a loop to change all the <p> tags:

myScript.js

let element =document.querySelector('H1')
element.textContent = 'Successfully changed'

let PElement =document.querySelectorAll('p')

PElement.forEach((para,index)=>{
	para.textContent = `Para ${index}: Paragraph changed using Javascript`
})

We used querySelectorAll for <p> tag which will give an array of all paragraphs in the HTML document so we can use forEach() method passed an arrow function and our webpage will change to...

DOM with JavaScript 11

Creating and Deleting the Elements [Section 4]:

We learned to change the text in an earlier section, now we will see how to create and delete any element.

We will use same HTML document in this section,

index.html

<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
	</head>
	<body>
		<p>This para is added via HTML</p>
		<script src="myScript.js"></script>
	</body>
</html>

Here there is only one paragraph tag in <body>.

Now we will see out myScript.js:

const myNewParaElement = document.createElement('p')
myNewParaElement.textContent = 'This para is via JS'
document.querySelector('body').appendChild(myNewParaElement)

Now,this line will create the paragraph element, let’s see how.

In the firstline, we used the document createElement()

method and passed p as a string for paragraph tag <p>. Now we got out paragraph tag but still, there is no text in it so we use what we learned in our last section to add text content in any tag.

So we have a complete paragraph element but it is not placed on the HTML document yet, so what we will do is , we add it to the HTML using the third statement of the myScript.js we used query selector and choose body (where we want to add it) and then we append (put at the last) our element as its child. Voila! We successfully created and added an element to our HTML document using JavaScript.

DOM with JavaScript 12

Now how to delete an element? It's pretty simple, let me demonstrate.

With same index.html we just make slightest addition into our myScript.js to remove one paragraph.

myScript.js

const myNewParaElement = document.createElement('p')
myNewParaElement.textContent = 'This para is via JS'

document.querySelector('body').appendChild(myNewParaElement)

document.querySelector('p').remove()

So we just added one line, to our previous version of myScript.js and this statement use a simple method remove() and it will remove that element.

DOM with JavaScript 13





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.