- How to use Javascript - innerText,Javascript - innerHTML.
- How to use Javascript - getElementsByTagName() method,getElementsByName(),GetElementsByClassName(),document.getElementById() method
- Styling DOM Elements in JavaScript using getElementById(),Class Name,Tag Name,CSS Selectors
- change paragraph background color,font style.
- .
- How to use getAttribute() method ,Setting Attributes and Removing Attributes from Html Elements
- change paragraph background color,font style.
- .
- How to Manipulating DOM Elements in JavaScript.
- _- change paragraph background color,font style.
- - insert div contain text on button click at the end of children
- - insert div contain text on button click at the beginning children
- - Get Set Inner HTML of an Element on button click and replace existing element
- - Insert HTML Element on button click without Replacing the Existing Content
- - Remove an child Element on button click_
- .
- How to Accessing the Child Nodes,Parent Nodes,Sibling Nodes.
- - How to Access or set Child text Color using firstChild,lastChild,lastElementChild
- - How to Access or set Child text Color using parentElement,parentNode
- - How to Access or set Child text Color using Sibling Nodes.
dom is hierarhy representation of all html element(head,body...) while we inspeting to debug error
=============================================================
html
Javascript
output
============================================
html
Javascript
output
html
Javascript
output
==================================
html
Javascript
output
30.How to use Javascript - innerText,Javascript - innerHTML.click here for solution
It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.
In this example, we are dynamically writing the html form inside the div name having the id mylocation. We are identifing this position by calling the document.getElementById() method.
WHEN U CLICK CCOMMENT BUTTON
Javascript - innerText
javascript innerText
The innerText property can be used to write the dynamic text on the html document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the validation message, password strength etc
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
31*.How to use Javascript - getElementsByTagName() method,getElementsByName(),GetElementsByClassName(),document.getElementById() method*click here for solution
Javascript - document.getElementById() method
document.getElementById() method to get value of the input text. But we need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Select an Element by its ID Attribute</title>
</head>
<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
var match = document.getElementById("mark");
// Highlighting element's background
match.style.background = "yellow";
</script>
</body>
</html>
Styling DOM Elements in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Add Inline Styles to an Element</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button" onclick="setStyle()">Set intro paragraph styles</button>
<script>
function setStyle() {
// Selecting element
var elem = document.getElementById("intro");
// Appling styles on element
elem.style.color = "blue";
elem.style.fontSize = "18px";
elem.style.fontWeight = "bold";
}
</script>
</body>
</html>
GetElementsByClassName()
The getElementsByClassName() method is used for selecting or getting the elements through their class name value. This DOM method returns an array-like object that consists of all the elements having the specified classname. On calling the getElementsByClassName() method on any particular element, it will search the whole document and will return only those elements which match the specified or given class name.
Syntax
var ele=document.getELementsByClassName('name');
Here, name is the mandatory argument to be passed. It is the string that specifies either a single classname or multiple class names to match.
Example of getElementsByClassName() Method
<html>
<head> <h5>DOM Methods </h5> </head>
<body>
<div class="Class">
This is a simple class implementation
</div>
<script type="text/javascript">
var x=document.getElementsByClassName('Class');
document.write("On calling x, it will return an arrsy-like object: <br>"+x);
</script>
</body>
</html>
Output:
** Javascript - document.getElementsByName() method**
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Output of the above example
Javascript - document.getElementsByTagName() method
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the document. To do this, we have called the document.getElementsByTagName("p") method that returns the total paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
30.*Styling DOM Elements in JavaScript using getElementById(),getElementById(),Class Name,Tag Name,CSS Selectors *
change paragraph background color,font style.
.click here for solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Select an Element by its ID Attribute</title>
</head>
<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
var match = document.getElementById("mark");
// Highlighting element's background
match.style.background = "yellow";
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Select Elements by Class Name</title>
</head>
<body>
<p class="test">This is a paragraph of text.</p>
<div class="block test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<hr>
<script>
// Selecting elements with class test
var matches = document.getElementsByClassName("test");
// Displaying the selected elements count
document.write("Number of selected elements: " + matches.length);
// Applying bold style to first element in selection
matches[0].style.fontWeight = "bold";
// Applying italic style to last element in selection
matches[matches.length - 1].style.fontStyle = "italic";
// Highlighting each element's background through loop
for(var elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
Selecting Elements by Tag Name
You can also select HTML elements by tag name using the getElementsByTagName() method. This method also returns an array-like object of all child elements with the given tag name.
ExampleTry this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Tag Name</title>
</head>
<body>
<p>This is a paragraph of text.</p>
<div class="test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting all paragraph elements
var matches = document.getElementsByTagName("p");
// Printing the number of selected paragraphs
document.write("Number of selected elements: " + matches.length);
// Highlighting each paragraph's background through loop
for(var elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
Selecting Elements with CSS Selectors
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS Selectors</title>
</head>
<body>
<ul>
<li>Bread</li>
<li class="tick">Coffee</li>
<li>Pineapple Cake</li>
</ul>
<script>
// Selecting all li elements
var matches = document.querySelectorAll("ul li");
// Printing the number of selected li elements
document.write("Number of selected elements: " + matches.length + "<hr>")
// Printing the content of selected li elements
for(var elem of matches) {
document.write(elem.innerHTML + "<br>");
}
// Applying line through style to first li element with class tick
matches = document.querySelectorAll("ul li.tick");
matches[0].style.textDecoration = "line-through";
</script>
</body>
</html>
31.How to use getAttribute() method ,Setting Attributes and Removing Attributes from Html Elements
change paragraph background color,font style.
.click here for solution
Getting Element's Attribute Value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Topmost Elements</title>
</head>
<body>
<script>
// Display lang attribute value of html element
alert(document.documentElement.getAttribute("lang")); // Outputs: en
// Set background color of body element
document.body.style.background = "yellow";
// Display tag name of the head element's first child
alert(document.head.firstElementChild.nodeName); // Outputs: meta
</script>
</body>
</html>
output:
Setting Attributes on Elements **
**Setting link href Attribute on text google
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Set an Attribute on an Element</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script>
// Selecting the element
var btn = document.getElementById("myBtn");
// Setting new attributes
btn.setAttribute("disabled", "");
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Change the Value of an Attribute</title>
</head>
<body>
<p><a href="#" id="myLink">Tutorial Republic</a></p>
<script>
// Selecting the element
var link = document.getElementById("myLink");
// Changing the href attribute value
link.setAttribute("href", "https://www.tutorialrepublic.com");
</script>
</body>
</html>
output:
Removing Attributes from Elements
*Remove link href Attribute *
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Remove an Attribute from an Element</title>
</head>
<body>
<a href="https://www.google.com/" id="myLink">Google</a>
<script>
// Selecting the element
var link = document.getElementById("myLink");
// Removing the href attribute
link.removeAttribute("href");
</script>
</body>
</html>
32.How to Manipulating DOM Elements in JavaScript.
_- change paragraph background color,font style.
- insert div contain text on button click at the end of children
- insert div contain text on button click at the beginning children
- Get Set Inner HTML of an Element on button click and replace existing element
- Insert HTML Element on button click without Replacing the Existing Content
- Remove an child Element on button click_
Adding New Elements to DOM
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Insert New Element into the DOM</title>
</head>
<body>
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<button type="button" onclick="insertElement()">Insert Element</button>
<script>
function insertElement() {
// Creating a new div element
var newDiv = document.createElement("div");
// Creating a text node
var newContent = document.createTextNode("Hi, how are you doing?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.appendChild(newDiv, currentDiv);
}
</script>
</body>
</html>
Adding New Elements before any child to DOM
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Insert New Element at the Beginning</title>
</head>
<body>
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<button type="button" onclick="insertElement()">Insert Element</button>
<script>
function insertElement() {
// Creating a new div element
var newDiv = document.createElement("div");
// Creating a text node
var newContent = document.createTextNode("Hi, how are you doing?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
</body>
</html>
*Setting Attributes on Elements on button click and replace existing element *
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Set Inner HTML of an Element</title>
</head>
<body>
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<button type="button" onclick="getContents()">Get Contents</button>
<button type="button" onclick="setContents()">Set Contents</button>
<script>
function getContents() {
// Getting inner HTML conents
var contents = document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents
}
function setContents() {
// Setting inner HTML contents
var mainDiv = document.getElementById("main");
mainDiv.innerHTML = "<p>This is <em>newly inserted</em> paragraph.</p>";
}
</script>
</body>
</html>
after get button click
after set button click
*Setting Attributes on Elements on button click and replace without existing element *
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Insert HTML without Replacing the Existing Content</title>
</head>
<body>
<!-- beforebegin -->
<div id="main">
<!-- afterbegin -->
<h1 id="title">Hello World!</h1>
<!-- beforeend -->
</div>
<!-- afterend -->
<button type="button" onclick="insertContent()">Insert Content</button>
<script>
function insertContent() {
// Selecting target element
var mainDiv = document.getElementById("main");
// Inserting HTML just before the element itself, as a previous sibling
mainDiv.insertAdjacentHTML('beforebegin', '<p>This is paragraph one.</p>');
// Inserting HTML just inside the element, before its first child
mainDiv.insertAdjacentHTML('afterbegin', '<p>This is paragraph two.</p>');
// Inserting HTML just inside the element, after its last child
mainDiv.insertAdjacentHTML('beforeend', '<p>This is paragraph three.</p>');
// Inserting HTML just after the element itself, as a next sibling
mainDiv.insertAdjacentHTML('afterend', '<p>This is paragraph four.</p>');
}
</script>
</body>
</html>
Removing Attributes from Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Remove an Element from the DOM</title>
</head>
<body>
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<button type="button" onclick="removeElement()">Remove Element</button>
<script>
function removeElement() {
var parentElem = document.getElementById("main");
var childElem = document.getElementById("hint");
parentElem.removeChild(childElem);
}
</script>
</body>
</html>
after remove button click
33.How to Accessing the Child Nodes,Parent Nodes,Sibling Nodes.
- How to Access or set Child text Color using firstChild,lastChild,lastElementChild
- How to Access or set Child text Color using parentElement,parentNode
- How to Access or set Child text Color using Sibling Nodes.
Note: The nodeName is a read-only property that returns the name of the current node as a string. For example, it returns the tag name for element node, #text for text node, #comment for comment node, #document for document node, and so on.
Tip: The topmost DOM tree nodes can be accessed directly as document properties. For example, the <html> element can be accessed with document.documentElement property, whereas the <head> element can be accessed with document.head property, and the <body> element can be accessed with document.body property.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get First and Last Child Nodes</title>
</head>
<body>
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = document.getElementById("main");
console.log(main.firstChild.nodeName); // Prints: #text
var hint = document.getElementById("hint");
console.log(hint.firstChild.nodeName); // Prints: SPAN
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Only Element Child Nodes</title>
</head>
<body>
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = document.getElementById("main");
console.log(main.firstElementChild.nodeName); // Prints: H1
main.firstElementChild.style.color = "red";
var hint = document.getElementById("hint");
console.log(hint.firstElementChild.nodeName); // Prints: SPAN
hint.firstElementChild.style.color = "blue";
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
output:
** Acces/set Child text Color using parentElement,parentNode**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Parent Node</title>
</head>
<body>
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var hint = document.getElementById("hint");
console.log(hint.parentNode.nodeName); // Prints: DIV
console.log(document.documentElement.parentNode.nodeName); // Prints: #document
console.log(document.parentNode); // Outputs: null
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Only Parent Element Node</title>
</head>
<body>
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var hint = document.getElementById("hint");
console.log(hint.parentNode.nodeName); // Prints: DIV
hint.parentNode.style.backgroundColor = "yellow";
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
** Access or set Child text Color using Sibling Nodes**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Previous and Next Sibling Element</title>
</head>
<body>
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p><hr>
</div>
<script>
var title = document.getElementById("title");
console.log(title.previousSibling.nodeName); // Prints: #text
var hint = document.getElementById("hint");
console.log(hint.nextSibling.nodeName); // Prints: HR
</script>
<p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
</body>
</html>
Top comments (0)