JavaScript is a client-side scripting language that runs in the browser. It is a high-level, interpreted language that does not require compilation. It can also run on the server-side using environments like Node.js. It adds interactivity, such as form validation, animations, dynamic updates, and more.
Modify Content in JavaScript
The getElementById()
method allows you to select an HTML element by its id
and modify its content or other properties.
Example: Find an element with the id
"example", and change its content to "Welcome to JavaScript!".
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p id="example">Original Content</p>
<!-- Click the below button to change the paragraph content. -->
<button type="button" onclick='document.getElementById("example").innerHTML = "Welcome to JavaScript!"'>Click Me!</button>
</body>
</html>
Note: JavaScript accepts both double and single quotes.
Modify Attribute Values in JavaScript
You can modify attribute values using JavaScript.
Example: Change the style
attribute value to update the font color from blue to red.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<!-- Initially, the paragraph text is blue. -->
<p id="example" style="color:blue;">Original Content</p>
<!-- When the below button is clicked, the text color of the paragraph will change to red. -->
<button type="button" onclick='document.getElementById("example").style.color = "red";'>Change Color</button>
</body>
</html>
Changing Multiple Styles
<!DOCTYPE html>
<html>
<body>
<h2>Modify HTML Styles with JavaScript</h2>
<p id="text" style="font-size: 16px; color: blue;">This is a sample paragraph.</p>
<button type="button" onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
const element = document.getElementById('text');
element.style.fontSize = '24px'; // Change the font size
element.style.color = 'red'; // Change the text color
element.style.fontWeight = 'bold'; // Make the text bold
}
</script>
</body>
</html>
To learn more about JavaScript, view the next tutorials in this guide.