When working with web development, selecting specific elements in your HTML is essential for styling with CSS or manipulating content using JavaScript. One of the most common ways to target an element is by using its id
attribute.
In this blog, we’ll explore how to select an element with the ID demo
using HTML, CSS, and JavaScript, with simple examples and best practices.
๐งฑ Step 1: Define the Element with id="demo"
You start by assigning the id
attribute to an HTML element:
<p id="demo">This is a paragraph with ID demo.</p>
The id
must be unique on the page โ only one element should have a specific id
.
๐จ Selecting #demo
in CSS
In CSS, you use the hash symbol (#
) to select an element by its ID.
โ Example:
#demo {
color: blue;
font-weight: bold;
}
This CSS rule will make the text of the element with ID demo
blue and bold.
๐ Selecting #demo
in JavaScript
In JavaScript, you can select the element using either:
1. document.getElementById()
const element = document.getElementById("demo");
element.innerHTML = "Text has been changed!";
2. document.querySelector()
const element = document.querySelector("#demo");
element.style.color = "green";
Both methods allow you to manipulate the elementโs content, styles, or attributes.
๐งพ Full Working Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select ID Demo</title>
<style>
#demo {
color: red;
font-size: 18px;
}
</style>
</head>
<body>
<p id="demo">Hello, I am the demo paragraph.</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
const demoElement = document.getElementById("demo");
demoElement.innerText = "You clicked the button!";
}
</script>
</body>
</html>
๐ง Best Practices
- Use IDs for unique elements (e.g., specific buttons, forms, or sections).
- Avoid using the same ID more than once.
- Prefer classes when styling multiple elements; use IDs for precise targeting.
๐ Conclusion
To select an element with the ID demo
, simply:
Task | Syntax |
---|---|
CSS | #demo { ... } |
JavaScript | document.getElementById("demo") or document.querySelector("#demo") |
Using IDs helps you precisely target and control elements in your web pages with both styling and scripting.