Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
JavaScript, the programming language that powers dynamic web content, becomes truly powerful when combined with the Document Object Model (DOM). The HTML DOM provides a structured representation of a document, allowing JavaScript to interact with and manipulate HTML elements. In this article, we’ll delve into essential JavaScript HTML DOM methods and explore their practical applications through examples.
getElementById()
method is a fundamental DOM method that allows you to access an HTML element by its unique identifier. Consider the following example: <!DOCTYPE html>
<html>
<body>
<p id="demo">Hello, World!</p>
<script>
var element = document.getElementById("demo");
element.innerHTML = "Greetings, Earth!";
</script>
</body>
</html>
Here, we retrieve the element with the ID “demo” and change its content using innerHTML
.
<!DOCTYPE html>
<html>
<body>
<p class="intro">This is an introduction.</p>
<p class="intro">Another introduction here.</p>
<script>
var elements = document.getElementsByClassName("intro");
for (var i = 0; i < elements.length; i++) {
elements[i].style.fontWeight = "bold";
}
</script>
</body>
</html>
In this example, we select all elements with the class “intro” and change their font weight to bold.
<!DOCTYPE html>
<html>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].style.color = "blue";
}
</script>
</body>
</html>
Here, we select all list items (<li>
) and change their text color to blue.
<!DOCTYPE html>
<html>
<body>
<script>
var newParagraph = document.createElement("p");
var textNode = document.createTextNode("This is a dynamically created paragraph.");
newParagraph.appendChild(textNode);
document.body.appendChild(newParagraph);
</script>
</body>
</html>
Here, createElement()
creates a new <p>
element, createTextNode()
creates a text node, and appendChild()
appends the text node to the paragraph, which is then appended to the body.
<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
</script>
</body>
</html>
When the button is clicked, an alert message will be displayed, showcasing the use of the addEventListener()
method.
Understanding and mastering JavaScript HTML DOM methods is essential for web developers. These methods provide the means to manipulate HTML elements dynamically, creating interactive and responsive web applications. By exploring and practicing these examples, developers can harness the full potential of JavaScript when working with the HTML DOM.