| title | DOM Document Object Model by Brian Bauska, Systems Analyst | ||
|---|---|---|---|
| author | bbauska | ||
| date created | 05/12/25 Mon 12+pm | ||
| date last editted | 05/12/25 Mon 8+pm | ||
| output |
|
- JavaScript - How to Manipulate DOM Elements?
- How to Add a Class to DOM Element in JavaScript?
- How to select DOM Elements in JavaScript?
- How to get all ID of the DOM elements with JavaScript?
- JavaScript – How to Get the Data Attributes of an Element?
- How To Get Element By Class Name In JavaScript?
- How to Get Value by Class Name using JavaScript?
- How to Get Domain Name From URL in JavaScript?
- How to get protocol, domain and port from URL using JavaScript?
- How to Extract the Host Name from URL using JavaScript?
- How to Get the Current URL using JavaScript?
- How to get URL Parameters using JavaScript?
- How to parse URL using JavaScript?
- Manipulating HTML Elements with JavaScript
- How to use innerHTML in JavaScript?
- JavaScript innerHTML
The DOM stands for the Document Object Model (DOM), which allows us to interact with the document and change its structure, style, and content. We can use the DOM to change the content and style of an HTML element by changing its properties.
We can manipulate or change the DOM elements by using the following methods:
You can change the content inside an HTML element using JavaScript. The two most common properties for this are innerHTML and textContent:
- innerHTML: Allows you to get or set the HTML content inside an element.
- textContent: Allows you to get or set the text content inside an element, ignoring any HTML tags.
<body>
<div id="example1">This is the original content using <b><mark>innerHTML</mark></b>.</div>
<div id="example2">This is the original text content using <b><mark>textContent</mark></b>.</div>
<button onclick="changeContent()">Change Content</button>
<script>
// Function to change content
function changeContent() {
document.getElementById("example1").innerHTML =
"<strong>This is changed using innerHTML!</strong>";
document.getElementById("example2").textContent =
"This is changed using textContent!";
}
</script>
</body>
- innerHTML changes the entire content of an element, including HTML tags. In this case, we replace the content of the first div with bold text using <strong>.
- textContent changes only the text inside the element, ignoring any HTML tags. The second div is updated with plain text, without any HTML formatting.
- The first div shows "This is the original content using innerHTML."
- The second div shows "This is the original text content using textContent."
- After clicking the "Change Content" button.
- The first div will display "This is changed using innerHTML!" with bold text.
- The second div will display "This is changed using textContent!" with plain text.
You can add, remove, or toggle classes on an element using JavaScript. This is helpful for styling or applying animations.
- classList.add(): Adds a class to an element.
- classList.remove(): Removes a class from an element.
- classList.toggle(): Toggles a class (adds it if it's not present, removes it if it is).
<html>
<head>
<style>
.highlight {
color: red;
font-weight: bold;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body>
<div id="example" class="bold">This is a text element with the "bold" class.</div>
<button onclick="addClass()">Add 'highlight' Class</button>
<button onclick="removeClass()">Remove 'bold' Class</button>
<button onclick="toggleClass()">Toggle 'highlight' Class</button>
<script>
function addClass() {
document.getElementById("example").classList.add("highlight");
}
function removeClass() {
document.getElementById("example").classList.remove("bold");
}
function toggleClass() {
document.getElementById("example").classList.toggle("highlight");
}
</script>
</body>
</html>
- Adding a Class (addClass()): When you click the "Add 'highlight' Class" button, the highlight class is added to the div element with the id="example". This changes the text color to red and makes it bold (as defined in the CSS).
- Removing a Class (removeClass()): When you click the "Remove 'bold' Class" button, the bold class is removed from the div, which removes the bold styling from the text.
- Toggling a Class (toggleClass()): When you click the "Toggle 'highlight' Class" button, the highlight class is either added or removed, depending on whether it's already present. If the class is present, it will be removed; if not, it will be added.
// Changing multiple CSS properties
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.fontSize = "20px";
// Adding more than one style
document.getElementById("demo").style.cssText = "color: blue; font-size: 18px;";
- document.createElement(): Creates a new element.
- appendChild(): Adds a new element to a parent element.
- removeChild(): Removes a child element from a parent.
// Create a new element
let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div";
// Add the new element to the DOM
document.body.appendChild(newDiv);
// Remove an element from the DOM
document.body.removeChild(newDiv);
// Create a new element
let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div";
// Find an existing element to insert before
let referenceNode = document.getElementById("referenceElement");
// Insert the new element before the reference element
document.body.insertBefore(newDiv, referenceNode);
- getAttribute(): Retrieves the value of an attribute.
- setAttribute(): Sets a new value for an attribute.
- removeAttribute(): Removes an attribute.
// Get the value of an attribute
let src = document.getElementById("image").getAttribute("src");
// Set a new value for an attribute
document.getElementById("image").setAttribute("src", "new-image.jpg");
// Remove an attribute
document.getElementById("image").removeAttribute("src");
- dataset: A special property in JavaScript that allows you to access data attributes.
// Setting a data attribute
document.getElementById("demo").dataset.userId = "12345";
// Getting a data attribute
let userId = document.getElementById("demo").dataset.userId;
console.log(userId); // Outputs: 12345
By using JavaScript, you can easily add, remove, or toggle classes on elements, making your web applications more interactive and responsive to user actions.
These are the following approaches:
- Using classList Property
- Using className Property
- Using classList Property
In this approach, we are using classList property to add the class into the DOM element. It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements. We will access the div using the getElementById and we will use the add property of classList to add a class.
element.classList.add("className")
<!DOCTYPE html>
<html>
<head>
<style>
.geek {
background-color: green;
font-size: 50px;
}
</style>
</head>
<body>
<button onclick="myClass()">Try it</button>
<div id="gfg">Geeks for Geeks</div>
<script>
function myClass() {
let elem = document.getElementById("gfg");
// Adding class to div element
elem.classList.add("geek");
}
</script>
</body>
</html>
HTMLElementObject.className
<!DOCTYPE html>
<html>
<head>
<style>
.geekClass {
background-color: green;
text-align: center;
font-size: 50px;
}
</style>
</head>
<body>
<div id="gfg">
Geeks For Geeks
</div>
<button onclick="myClassName()">Add Class</button>
<script>
function myClassName() {
let element = document.getElementById("gfg");
// Adding the class geekClass to element
// with id gfg space is given in className
// (" geekClass") as if there is already
// a class attached to an element than our
// new class won't overwrite and will append
// one more class to the element
element.className += " geekClass";
}
</script>
</body>
</html>
Below are the approaches to select DOM elements in JavaScript:
- Using getElementById
- Using getElementsByClassName
- Using getElementsByTagName
- Using querySelector
- Using querySelectorAll
document.getElementById('id')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>getElementById Example</title>
</head>
<body>
<h1 id="gfg">GeeksForGeeks</h1>
<script>
// styling the h1 tag
const element = document.getElementById('gfg');
element.style.color = "green";
element.style.textAlign = "center";
element.style.margin = "30px";
element.style.fontSize = "30px";
</script>
</body>
</html>
This method selects elements based on their class attribute. It returns a collection of elements with the specified class name.
document.getElementsByClassName('class')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>getElementsByClassName Example</title>
</head>
<body>
<h1 class="selector">GeeksForGeeks</h1>
<h2 class="selector">DOM selector in JavaScript</h2>
<script>
const elements =
documSizeent.getElementsByClassName('selector');
elements[0].style.color = "green";
elements[1].style.color = "red";
elements[0].style.textAlign = "center";
elements[1].style.textAlign = "center";
elements[0].style.marginTop = "60px";
</script>
</body>
</html>
This method selects elements based on their tag name. It returns a collection of elements with the specified tag name.
document.getElementsByTagName('tag')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>getElementsByTagName Example</title>
</head>
<body>
<p>Thanks for visiting GFG</p>
<p>This is showing how to select DOM element using tag name</p>
<script>
const paragraphs = document.getElementsByTagName('p');
paragraphs[0].style.color = "green";
paragraphs[1].style.color = "blue";
paragraphs[0].style.fontSize = "25px";
paragraphs[0].style.textAlign = "center";
paragraphs[1].style.textAlign = "center";
paragraphs[0].style.marginTop = "60px";
</script>
</body>
</html>
This method selects the first element that matches a specified CSS selector. It returns only one element.
document.querySelector('selector')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>querySelector Example</title>
</head>
<body>
<div class="gfg">GeeksForGeeks</div>
<script>
const element =
document.querySelector('.gfg');
element.style.color = "green";
element.style.textAlign = "center";
element.style.margin = "30px";
element.style.fontSize = "30px";
</script>
</body>
</html>
Similar to querySelector, but it returns a NodeList containing all elements that match the specified CSS selector.
document.querySelectorAll('selector')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>querySelectorAll Example</title>
</head>
<body>
<h1 class="selector">GeeksForGeeks</h1>
<p class="selector">
This is showing how to select DOM element
using tag name
</p>
<script>
const elements = document.querySelectorAll('.selector');
elements[0].style.color = "green";
elements[1].style.color = "red";
elements[0].style.textAlign = "center";
elements[1].style.textAlign = "center";
elements[0].style.marginTop = "60px";
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get all ID of the DOM
elements with JavaScript ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
Click on the button to get
all IDs in an array.
</p>
<button onclick="muFunc()">
Click Here
</button>
<p id="GFG"></p>
<script>
let res = document.getElementById("GFG");
function muFunc() {
let ID = [];
$("*").each(function () {
if (this.id) {
ID.push(this.id);
}
});
res.innerHTML = ID;
}
</script>
</body>
</html>
- First select all elements using $(‘*’) selector, which selects every element of the Document.
- Use .map() method to traverse all element and check if it has ID.
- If it has ID then push it in the array using .get() method.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get all ID of the DOM
elements with JavaScript ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
Click on the button to get
all IDs in an array.
</p>
<button id="Geeks" onclick="muFunc()">
Click Here
</button>
<p id="GFG"></p>
<script>
let res = document.getElementById("GFG");
function muFunc() {
let ID = [];
ID = $("*").map(function() {
if (this.id) {
return this.id;
}
}).get();
res.innerHTML = ID;
}
</script>
</body>
</html>
const e = document.getElementByID('demo') // Accessing the element
const dataId = e.dataset.dataID //Access the data-id attribute
<!DOCTYPE html>
<html>
<body>
<div
id="element"
data-typeId="123"
data-name="name"
data-points="10"
data-important="true">
This is the Target Element.
</div>
<br />
<button onclick="myFunction()">
Get Attributes
</button>
<p id="result"></p>
<script>
let result = document.getElementById("result");
let e = document.getElementById("element");
function myFunction() {
let jsonData = JSON.stringify({
id: parseInt(e.dataset.typeid),
points: parseInt(e.dataset.points),
important: e.dataset.important,
dataName: e.dataset.name
});
result.innerHTML = jsonData;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div
id="target"
data-typeId="123"
data-name="name"
data-points="10"
data-important="true"
>
This is the Target Element.
</div>
<br />
<button onclick="myFunction()">Get Attributes</button>
<p id="result"></p>
<script>
let result = document.getElementById("result");
let e = document.getElementById("target");
function myFunction() {
let jsonData = JSON.stringify({
id: parseInt(e.getAttribute('data-typeId')),
points: parseInt(e.getAttribute('data-points')),
important: e.getAttribute('data-important'),
dataName: e.getAttribute('data-name')
});
result.innerHTML = jsonData;
}
</script>
</body>
</html>
Below are the following approaches to get elements by class name in Javascript:
- Using document.getElementsByClassName()
- Using document.querySelector()
- Using document.querySelectorAll()
var elements = document.getElementsByClassName("className");Example: In this example we are using the getElementsByClassName() method to get element by class name in javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Get Elements by Class Name</title>
<style>
.output {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="output" id="output1"></div>
<script>
var boxes =
document.getElementsByClassName("box");
var output =
document.getElementById("output1");
output.innerHTML =
"Number of boxes: " + boxes.length;
</script>
</body>
</html>
Syntax:
var element = document.querySelector(".className");
Example: In this example we are using the querySelector() method to get element by class name and we will change the background color of selected class in javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,'' initial-scale=1.0">
<title>Query Selector Example</title>
<style>
.box {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<script>
var firstBox =
document.querySelector(".box");
firstBox.style.backgroundColor =
"lightblue"; // Change the background color to light blue
firstBox.style.color = "white"; // Change the text color to white
</script>
</body>
</html>
Syntax:
var elements = document.querySelectorAll(".className");
Example: In below example we are using the querySelectorAll and we will print all the content which have that class name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Query Selector All Example</title>
<style>
.output {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="output" id="output3"></div>
<script>
var allBoxes =
document.querySelectorAll(".box");
var output =
document.getElementById("output3");
var content = "Contents of all boxes: <br>";
allBoxes.forEach(function (box) {
content += box.innerText + "<br>";
});
output.innerHTML = content;
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Get Value by Class Name</title>
</head>
<body style="text-align: center;">
<h1 class="heading">
GeeksforGeeks
</h1>
<p class="para">
A computer science portal for geeks
</p>
<button onclick="myGeeks()">
Get Value
</button>
<p id="result"></p>
<script>
function myGeeks() {
// Get elements with the class name 'heading'
let headingElements =
document.getElementsByClassName('heading');
// Check if any elements with the
// specified class name exist
if (headingElements.length > 0) {
// Access the value of the first
// element in the collection
let headingVal = headingElements[0].innerHTML;
// Update the content of the 'result' element
document.getElementById('result')
.innerHTML = headingVal;
} else {
console.log(
'Element with class name "heading" not found.');
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Get Value by Class Name</title>
</head>
<body style="text-align: center;">
<h1 class="heading text">
GeeksforGeeks
</h1>
<p class="para text">
A computer science portal for geeks
</p>
<button onclick="myGeeks()">
Get Value
</button>
<p id="result"></p>
<script>
function myGeeks() {
// Get elements with the class name 'heading'
let headingElements =
document.getElementsByClassName('text');
// Check if any elements with the
// specified class name exist
if (headingElements.length > 0) {
// Access the value of the first
// element in the collection
let headingVal = headingElements[1].innerHTML;
// Update the content of the 'result' element
document.getElementById('result')
.innerHTML = headingVal;
} else {
console.log(
'Element with class name "text" not found.');
}
}
</script>
</body>
</html>
Below are the following approaches to get a domain name from a URL in Javascript:
- Using the URL Object - Using Regular Expressions The new URL(url) constructor parses the URL and creates a URL object. This object has various properties that represent different parts of the URL. The hostname property of the URL object returns the domain name. For instance, for the URL https://www.example.com/path/to/resource?query=param, urlObject.hostname would return www.example.com. If the URL is invalid, the URL constructor will throw an error. In the catch block, you can handle this error, for example by logging it or returning a default value.<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>How to get domain name from URL in JavaScript</h1>
<p>Domain Name : <span id="span"></span></p>
<script src="Index.js"> </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>How to get domain name from URL in JavaScript</h1>
<p>Domain Name : <span id="span"></span></p>
<script src="Index.js"> </script>
</body>
</html>
Method 1: Using location.protocol, location.hostname, location.port methods: The location interface has various methods that can be used to return the required properties.
- The location.protocol property is used to return the protocol scheme of the URL along with the final colon(:).
- The location.hostname is used to return the domain name of the URL.
- The location.port property is used to return the port of the URL. It returns nothing if the port is not described explicitly in the URL.
protocol = location.protocol;
domain = location.hostname;
port = location.port;
<!DOCTYPE html>
<html>
<head>
<title>
Get protocol, domain, and port from URL
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Get protocol, domain, and port from URL
</b>
<p>
Protocol is:
<span class="protocol"></span>
</p>
<p>
Domain is:
<span class="domain"></span>
</p>
<p>
Port is:
<span class="port"></span>
</p>
<button onclick="getDetails()">
Get protocol, domain, port
</button>
<script type="text/javascript">
function getDetails() {
protocol = location.protocol;
domain = location.hostname;
port = location.port;
document.querySelector('.protocol').textContent
= protocol;
document.querySelector('.domain').textContent
= domain;
document.querySelector('.port').textContent
= port;
}
</script>
</body>
</html>
- After Clicking the button:
Method 2: Using the URL interface: The URL interface is used to represent object URL. It can be used for getting the port, domain, and protocol as it has inbuilt methods to get these values.
- The url.protocol property is used to return the protocol scheme of the URL along with the final colon(:).
- The url.hostname is used to return the domain of the URL.
- The url.port property is used to return the port of the URL. It returns ” if the port is not described explicitly.
Note: This API is not supported in Internet Explorer 11.
current_url = window.location.href;
url_object = new URL(current_url);
protocol = url_object.protocol;
domain = url_object.hostname;
port = url_object.port;
<!DOCTYPE html>
<html>
<head>
<title>
Get protocol, domain, and port from URL
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Get protocol, domain, and port from URL
</b>
<p>Protocol is: <span class="protocol"></span></p>
<p>Domain is: <span class="domain"></span></p>
<p>Port is: <span class="port"></span></p>
<button onclick="getDetails()">
Get protocol, domain, port
</button>
<script type="text/javascript">
function getDetails() {
current_url = window.location.href;
url_object = new URL(current_url);
protocol = url_object.protocol;
domain = url_object.hostname;
port = url_object.port;
document.querySelector('.protocol').textContent
= protocol;
document.querySelector('.domain').textContent
= domain;
document.querySelector('.port').textContent
= port;
}
</script>
</body>
</html>
- After Clicking the button:
window.location.propertyname
Example : In this example, we will use the self URL, where the code will run to extract the hostname.
<!DOCTYPE html>
<html>
<head>
<title>
Get domain from URL
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>URL is:</b>
<script>
document.write(window.location.href);
</script>
<br>
<b>hostname is:</b>
<script>
document.write(window.location.hostname);
</script>
</body>
</html>
url3.indexOf("://");
Example : In this example, we will ask for the URL to the user and then will perform the extraction of the hostname on that URL.
<!DOCTYPE html>
<html>
<head>
<title>Extracting URL</title>
</head>
<body>
<h1 style="color: green;">GeeksforGeeks</h1>
<b>Extracting URL</b>
<br><br>
<form name="f1">
<input type="text" name="txt" placeholder="Paste URL" />
<input type="button" value="click" onclick="url2()" />
</form>
<script>
function url2() {
let url3 = document.f1.txt.value;
let j = url3.indexOf("://");
let host = "";
for (i = j + 3; i < url3.length; i++) {
if (url3.charAt(i) != '/') {
host = host + "" + url3.charAt(i);
} else {
break;
}
}
document.write(host);
}
</script>
</body>
</html>
document.URL
<script>
// Get the current URL using document.URL
let currentUrl = document.URL;
// Log the URL to the console
console.log(currentUrl);
</script>
http://127.0.0.1:5500/index.htmlThe window.location.href property of the HTML DOM Window object returns a string containing the URL of the current page. This property is part of the Location object, which contains information about the current location of the document.
window.location.href
<script>
// Get the current URL using document.URL
let currentUrl = document.URL;
// Log the URL to the console
console.log(currentUrl);
</script>
http://127.0.0.1:5500/index.html
Note: Use the HTML file to copy paste and run the given code and you can see the output in the console, it will print the URL.
To get URL parameters using JavaScript means extracting the query string values from a URL. URL parameters, found after the ? in a URL, pass data like search terms or user information. JavaScript can parse these parameters, allowing you to programmatically access or manipulate their values.For getting the URL parameters, there are 2 ways:
- Using the URLSearchParams Object - Separating and accessing each parameter pair The URLSearchParams interface provides methods to work with URL parameters. After splitting the URL with ?, the parameters part is passed to URLSearchParams(). Using entries(), you retrieve key/value pairs, allowing access to all URL parameters for further use.let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
for (let pair of queryString.entries()) {
console.log("Key is: " + pair[0]);
console.log("Value is: " + pair[1]);
}
Example: In this example we retrieves URL parameters using JavaScript. It splits the URL, extracts parameters with URLSearchParams(), and logs each key-value pair to the console when the button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>
How To Get URL Parameters using JavaScript?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<b>
How To Get URL Parameters
With JavaScript?
</b>
<p> The url used is:
https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks
</p>
<p>
Click on the button to get the url
parameters in the console.
</p>
<button onclick="getParameters()"> Get URL parameters </button>
<script>
function getParameters() {
let urlString =
"https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks";
let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
for(let pair of queryString.entries()) {
console.log("Key is:" + pair[0]);
console.log("Value is:" + pair[1]);
}
}
</script>
</body>
</html>
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
for (let i = 0; i < params_arr.length; i++) {
let pair = params_arr[i].split('=');
console.log("Key is:", pair[0]);
console.log("Value is:", pair[1]);
}
Example: In this example we retrieves URL parameters by splitting the URL string manually. It extracts each key-value pair, splits them, and logs the results in the console when the button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>
How To Get URL Parameters using JavaScript?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1> <b>
How To Get URL Parameters
With JavaScript?
</b>
<p> The url used is:
https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks
</p>
<p>
Click on the button to get the url
parameters in the console.
</p>
<button onclick="getParameters()"> Get URL parameters </button>
<script>
function getParameters() {
let urlString =
"https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks";
let paramString = urlString.split('?')[1];
let params_arr = paramString.split('&');
for(let i = 0; i < params_arr.length; i++) {
let pair = params_arr[i].split('=');
console.log("Key is:" + pair[0]);
console.log("Value is:" + pair[1]);
}
}
</script>
</body>
</html>
URL: https://www.geeksforgeeks.org/courses
When we parse the above URL then we can find
hostname: geeksforgeeks.com
path: /courses
Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL.
// Store the URL into variable
var url = "https://geeksforgeeks.org/pathname/?search=query";
// Created a parser using createElement() method
var parser = document.createElement("a");
parser.href = url;
// Host of the URL
console.log(parser.host);
// Hostname of the URL
console.log(parser.hostname );
// Pathname of URL
console.log(parser.pathname);
// Search in the URL
console.log(parser.search );geeksforgeeks.org
geeksforgeeks.org
/pathname/
?search=query
Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.
// Store the URL into variable
var url =
"https://geeksforgeeks.org:3000/pathname/?search=query";
// Created a URL object using URL() method
var parser = new URL(url);
// Protocol used in URL
console.log(parser.protocol);
// Host of the URL
console.log(parser.host);
// Port in the URL
console.log(parser.port);
// Hostname of the URL
console.log(parser.hostname);
// Search in the URL
console.log(parser.search);
// Search parameter in the URL
console.log(parser.searchParams);https:
geeksforgeeks.org:3000
3000
geeksforgeeks.org
?search=query
search=query
Methods to Identify the elements to manipulate: There are several methods to identify the HTML elements that we want to manipulate using JavaScript. The most common methods are:
- Using the element's ID: We can assign an ID to an HTML element and use document.getElementById() to access it.
- Using the element's class name: We can assign a class name to an HTML element and use document.getElementsByClassName() to access it.
- Using the element's tag name: We can use document.getElementsByTagName() to access all elements with a particular tag name.
Accessing the properties of the elements: Once we have identified the HTML element that we want to manipulate, we can access its properties using JavaScript. For example, to access the text content of an element, we can use the innerHTML property. Similarly, we can access the style properties of an element using the style property.
Use Event Listeners to Respond to User Interactions: We can use event listeners to respond to user interactions such as clicking a button or hovering over an element. Event listeners are functions that are executed when a particular event occurs. For example, we can use the onclick event listener to execute a function when a button is clicked.
When building a website or web application, it's common to need to access and manipulate HTML elements using JavaScript. There are several methods available in JavaScript that allow you to do this, including getElementById(), getElementsByClassName(), and getElementsByTagName(). In this article, we'll take a systematic approach to use these methods and show you how to access and manipulate elements in your HTML documents.
The first step in working with HTML elements in JavaScript is to identify the element you want to manipulate. There are several ways to do this, depending on the specific element you're trying to access. Here are some common methods:- getElementById() Method: Use this method to access an element with a specific ID. IDs should be unique within an HTML document, so this method will always return a single element.
- getElementsByClassName() Method: Use this method to access all elements with a specific class name. Multiple elements can have the same class name, so this method will return a collection of elements.
- getElementsByTagName() Method: Use this method to access all elements with a specific tag name. Multiple elements can have the same tag name, so this method will also return a collection of elements.
let element = document.getElementById("my-id");
let elements = document.getElementsByClassName("myClass");
let elements = document.getElementsByTagName("p");
// Accessing an element's methods
element.innerHTML = "New content!"; // changes the content of the element
element.classList.add("newClass"); // adds a new CSS class to the element
element.style.backgroundColor = "red"; // changes the background color of the element
<button id="myButton">Click me!</button>
<script>
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
</script>
In this example, we use getElementById() to access a button element with the ID "myButton". We then add an event listener to the button using the addEventListener() method. The event we're listening for is a "click" event, which is triggered when the user clicks the button. When the event is triggered, the function we passed as the second argument is executed, which logs a message to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<title>document.getElementById()</title>
</head>
<body>
<h1 id="my-id">Hello World!</h1>
<script>
// Get element with id "my-id"
var elements = document.getElementById("my-id");
// Change the content of the element
elements.innerHTML = "New content!";
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>document.getElementsByClassName()</title>
</head>
<body>
<p class="myClass">This is a paragraph.</p>
<p class="myClass">This is another paragraph.</p>
<script>
// Get all elements with class "myClass"
var elements = document.getElementsByClassName("myClass");
// Change the content of the first element
elements[0].innerHTML = "New content!";
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Manipulation</title>
</head>
<body>
<h1 id="my-heading">Hello, World!</h1>
<button id="my-button">Click me!</button>
<script>
const heading = document.getElementById("my-heading");
const button = document.getElementById("my-button");
button.addEventListener("click", function () {
heading.innerHTML = "Button clicked";
heading.style.color = "red";
});
</script>
</body>
</html>
Explanation: In this example, we first access the button element using the getElementById() method. We then add an event listener to the button using the addEventListener() method. The event we are listening for is the "click" event, and the function we want to execute when the event occurs is defined inline.
Conclusion: In conclusion, manipulating HTML elements with JavaScript is a powerful technique that can be used to create dynamic and interactive web pages. By using the methods discussed above, we can identify and access the HTML elements on a web page and modify their properties to create the desired behavior.
The innerHTML property in JavaScript allows you to get or set the HTML content of an element as a string.let element = document.getElementById("myElementId");
let htmlContent = element.innerHTML;
let element = document.getElementById("myElementId");
element.innerHTML = "New HTML content";
<div id="myElement">Initial content</div>
let element = document.getElementById("myElement");
let htmlContent = element.innerHTML;
console.log(htmlContent);
// Output: Initial content
element.innerHTML = "<b>New content</b>";
console.log(element.innerHTML);
// Output: <b>New content</b>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>innerHTML Example</title>
<style>
.container {
padding: 10px;
}
</style>
</head>
<body>
<div class="container" id="myElement">Initial content</div>
<button onclick="changeContent()">Change Content</button>
<script>
function changeContent() {
let element = document.getElementById("myElement");
element.innerHTML = "<b>New content</b>";
}
</script>
</body>
</html>
The innerHTML property in JavScript is used to append the dynamic HTML or text content to an element using JavaScript. It is designed to add dynamic HTML, but developers also use it to add text content as well. It can be directly used with the element by selecting it using DOM manipulation.
selctedHTMLElement.innerHTML = "contentToAppend";
Example 1: The below code shows a basic implementation of innerHTML property to append HTML directly to an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>
JavaScript innerHTML
</title>
<style>
#container{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h2>
The below content is added dynamically
using the innerHTML property in JavaScript.
</h2>
</div>
<script>
const container = document.getElementById('container');
container.innerHTML +=
`
<h3>
Hey Geek, <br/>
Welcome to GeeksforGeeks
</h3>
<p>
This content is added using the
innerHTML property.
</p>
`;
</script>
</body>
</html>
Example 2: The below code implements the innerHTML property with click event to add HTML onclick to the button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>
JavaScript innerHTML
</title>
<style>
#container {
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h2>
Click the below button to dynamically add
the HTML using the innerHTML property.
</h2>
<button id="myBtn">Add HTML</button>
</div>
<script>
const myBtn = document.getElementById('myBtn');
function clickHandler() {
const container =
document.getElementById('container');
container.innerHTML +=
`
<h3>
Hey Geek, <br/>
Welcome to GeeksforGeeks
</h3>
<p>
This content is added using
the innerHTML property.
</p>
`;
}
myBtn.addEventListener('click', clickHandler);
</script>
</body>
</html>