JavaScript - DOM MethodsAbout Document Object Model(DOM) :When a web page is loaded, the browser creates a Document Object Model of the page.With the object model, JavaScript gets all the power it needs to create dynamic HTML:The HTML DOM model is constructed as a tree of Objects : HTML DOM methods are actions you can perform (on HTML Elements).HTML DOM properties are values (of HTML Elements) that you can set or change. The DOM Programming Interface : The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects.The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element).A method is an action you can do (like add or deleting an HTML element). Eg : The following example changes the content (the innerHTML) of the < p> element with id="demo": < !DOCTYPE html> < html> < body> < h2>Web Page< /h2> < p id="demo">< /p> < script> document.getElementById("demo").innerHTML = "Hi This is DOM Method!"; < /script> < /body> < /html>Output : Web PageHi This is DOM Method! In the example above, getElementById is a method, while innerHTML is a property. The getElementById Method : The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method used id="demo" to find the element. The innerHTML Property : The easiest way to get the content of an element is by using the innerHTML property.The innerHTML property is useful for getting or replacing the content of HTML elements. Note : The innerHTML property can be used to get or change any HTML element, including < html> and < body>. HTML DOM Document Object :The document object represents your web page.If you want to access any element in an HTML page, you always start with accessing the document object. Below are some examples of how you can use the document object to access and manipulate HTML.Finding HTML Elements : Method Description --------------------------- ----------------------------------------- document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name Changing HTML Elements : Property Description -------------------------------------- ------------------------------------------ element.innerHTML = new html content Change the inner HTML of an element element.attribute = new value Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element Method Description -------------------------------------- -------------------------------------------------- element.setAttribute(attribute, value) Change the attribute value of an HTML element Adding and Deleting Elements : Method Description --------------------------- -------------------------------------------------- document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(new, old) Replace an HTML element document.write(text) Write into the HTML output stream Adding Events Handlers Method Description ------------------------------------------------------- -------------------------------------------------- document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event DOM Elements :Finding HTML Elements :Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first. There are several ways to do this: Finding HTML Element by Id & ClassName: < !DOCTYPE html> < html> < body> < h2>JavaScript HTML DOM< /h2> < p id="intro">Finding HTML Elements by Id< /p> < p>This example demonstrates the < b>getElementsById< /b> method.< /p> < p id="demo">< /p> < br> < p>Finding HTML Elements by Class Name.< /p> < p class="intro1">This example demonstrates the < b>getElementsByClassName< /b> method.< /p> < p id="demo1">< /p> < script> const element = document.getElementById("intro"); document.getElementById("demo").innerHTML = "The text in intro paragraph is: " + element.innerHTML; const x = document.getElementsByClassName("intro1"); document.getElementById("demo1").innerHTML = 'The first paragraph (index 0) with class="intro1" is: ' + x[0].innerHTML; < /script> < /body> < /html>Output : JavaScript HTML DOMFinding HTML Elements by Id This example demonstrates the getElementsById method. The text in intro paragraph is: Finding HTML Elements by Id Finding HTML Elements by Class Name. This example demonstrates the getElementsByClassName method. The first paragraph (index 0) with class="intro1" is: This example demonstrates the getElementsByClassName method. Finding HTML elements by Tag Name : < !DOCTYPE html> < html> < body> < h2>JavaScript HTML DOM< /h2> < p>Finding HTML Elements by Tag Name.< /p> < p>This example demonstrates the < b>getElementsByTagName< /b> method.< /p> < p id="demo"> < script> const element = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' + element[0].innerHTML; < /script> < /body> < /html>Output : JavaScript HTML DOMFinding HTML Elements by Tag Name. This example demonstrates the getElementsByTagName method. The text in first paragraph (index 0) is: Finding HTML Elements by Tag Name. Finding HTML Elements by CSS Selectors : If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all < p> elements with class="intro". < !DOCTYPE html> < html> < body> < h2>JavaScript HTML DOM< /h2> < p>Finding HTML Elements by Query Selector< /p> < p class="intro">Hello World!.< /p> < p class="intro">This example demonstrates the < b>querySelectorAll< /b> method.< /p> < p id="demo">< /p> < script> const x = document.querySelectorAll("p.intro"); document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML; < /script> < /body> < /html>Output : JavaScript HTML DOMFinding HTML Elements by Query Selector Hello World!. This example demonstrates the querySelectorAll method. The first paragraph (index 0) with class="intro" is: Hello World!. Finding HTML elements by HTML object collections : < !DOCTYPE html> < html> < body> < h2>JavaScript HTML DOM< /h2> < p>Finding HTML Elements Using < b>document.forms< /b>.< /p> < form id="frm1" action="/action_page.php"> First name: < input type="text" name="fname" value="Banu Prakash">< br> Last name: < input type="text" name="lname" value="Elapan">< br>< br> < input type="submit" value="Submit"> < /form> < p>These are the values of each element in the form:< /p> < p id="demo">< /p> < script> const x = document.forms["frm1"]; let text = ""; for (let i = 0; i < x.length ;i++) { text += x.elements[i].value + "< br>"; } document.getElementById("demo").innerHTML = text; < /script> < /body> < /html>Output : JavaScript HTML DOMFinding HTML Elements Using document.forms. These are the values of each element in the form: Banu Prakash Elapan Submit DOM HTML :< !DOCTYPE html> < html> < body> < h1 id="id01">Old Heading< /h1> < p>JavaScript changed "Old Heading" to "New Heading".< /p> < h1>Changing image1 to image2< /h1> < img id="myImage" src="smiley.gif"> < h1>Writing content through JS < /h1> < p>Bla bla bla< /p> < script> const element = document.getElementById("id01"); element.innerHTML = "New Heading"; document.getElementById("myImage").src = "landscape.jpg"; document.write(Date()); < /script> < /body> < /html>Output : Old HeadingJavaScript changed "Old Heading" to "New Heading". Changing image1 to image2![]() Writing content through JSBla bla bla Mon Oct 14 2024 16:30:18 GMT+0530 (India Standard Time) JavaScript Forms :< !DOCTYPE html> < html> < head> < script> function validateForm() { let x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; } } < /script> < /head> < body> < h2>JavaScript Validation< /h2> < form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post"> Name: < input type="text" name="fname"> < input type="submit" value="Submit"> < /form> < /body> < /html>Output : JavaScript Can Validate Numeric Input : JavaScript is often used to validate numeric input: < !DOCTYPE html> < html> < body> < h2>JavaScript Validation< /h2> < p>Please input a number between 1 and 10:< /p> < input id="numb"> < button type="button" onclick="myFunction()">Submit< /button> < p id="demo">< /p> < script> function myFunction() { // Get the value of the input field with id="numb" let x = document.getElementById("numb").value; // If x is Not a Number or less than one or greater than 10 let text; if (isNaN(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text; } < /script> < /body> < /html>Output : JavaScript ValidationPlease input a number between 1 and 10: JavaScript HTML DOM - Changing CSS :Changing HTML Style : To change the style of an HTML element, use this syntax:document.getElementById(id).style.property = new styleThe following example changes the style of a < p> element: < !DOCTYPE html> < html> < body> < h2>JavaScript HTML DOM< /h2> < p>Changing the HTML style:< /p> < p id="p1">Hello World!< /p> < p id="p2">Hello World!< /p> < script> document.getElementById("p2").style.color = "blue"; document.getElementById("p2").style.fontFamily = "Arial, Helvetica, sans-serif;"; document.getElementById("p2").style.fontSize = "larger"; < /script> < /body> < /html>Output : JavaScript HTML DOMChanging the HTML style: Hello World! Hello World! Using Events : The HTML DOM allows you to execute code when an event occurs.Events are generated by the browser when "things happen" to HTML elements: < !DOCTYPE html> < html> < body> < h1 id="id1">My Heading 1< /h1> < button type="button" onclick="document.getElementById('id1').style.color = 'red'"> Click Me!< /button> < /body> < /html>Output : My Heading 1Create the Full Animation Using JavaScript :< !DOCTYPE html> < html> < style> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; } < /style> < body> < p>< button onclick="myMove()">Click Me< /button>< /p> < div id ="container"> < div id ="animate">< /div> < /div> < script> function myMove() { let id = null; const elem = document.getElementById("animate"); let pos = 0; clearInterval(id); id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + "px"; elem.style.left = pos + "px"; } } } < /script> < /body> < /html>Output : JavaScript HTML DOM Events :Reacting to Events :A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick=JavaScriptExamples of HTML events: In this example, the content of the < h1> element is changed when a user clicks on it: < !DOCTYPE html> < html> < body> < h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!< /h1> < /body> < /html>In this example, a function is called from the event handler: < !DOCTYPE html> < html> < body> < h1>JavaScript HTML Events < h2>The onclick Attribute < h2 onclick="changeText(this)">Click on this text! < script> function changeText(id) { id.innerHTML = "Ooops!"; } < /script> < /body> < /html>Output : JavaScript HTML EventsThe onclick AttributeClick on this text!The onmouseover and onmouseout Events : The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element: < !DOCTYPE html> < html> < body> < h1>JavaScript HTML Events< /h1> < h2>The onmouseover Attribute< /h2> < div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-color:#D94A38;width:150px; "> Mouse Over Me< /div> < script> function mOver(obj) { obj.innerHTML = "Thank You" } function mOut(obj) { obj.innerHTML = "Mouse Over Me" } < /script> < /body> < /html>Output : JavaScript HTML EventsThe onmouseover AttributeMouse Over Me The onmousedown, onmouseup and onclick Events : The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered. < !DOCTYPE html> < html> < body> < h1>JavaScript HTML Events< /h1> < h2>The onmousedown Attribute< /h2> < div onmousedown="mDown1(this)" onmouseup="mUp1(this)" style="background-color:#D94A38;width:150px;"> Click Me< /div> < script> function mDown1(obj) { obj.style.backgroundColor = "#1ec5e5"; obj.innerHTML = "Release Me"; } function mUp1(obj) { obj.style.backgroundColor="#D94A38"; obj.innerHTML="Thank You"; } < /script> < /body> < /html>Output : JavaScript HTML EventsThe onmousedown AttributeClick Me There are many examples : More Examples onmousedown and onmouseup Change an image when a user holds down the mouse button. onload Display an alert box when the page has finished loading. onfocus Change the background-color of an input field when it gets focus. Mouse Events Change the color of an element when the cursor moves over it. JavaScript HTML DOM EventListener :< !DOCTYPE html> < html> < body> < h2>JavaScript addEventListener()< /h2> < p>This example uses the addEventListener() method to attach a click event to a button.< /p> < button id="myBtn">Try it< /button> < p id="demobtn">< /p> < script> document.getElementById("myBtn").addEventListener("click", displayDate); function displayDate() { document.getElementById("demobtn").innerHTML = Date(); } < /script> < /body> < /html>Output : JavaScript addEventListener()This example uses the addEventListener() method to attach a click event to a button. « Previous Next Topic » (JS - Event, Event Handler, Event Listener) |