How Do You Select an Element with ID demo in HTML/CSS/JavaScript?

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:

TaskSyntax
CSS#demo { ... }
JavaScriptdocument.getElementById("demo") or document.querySelector("#demo")

Using IDs helps you precisely target and control elements in your web pages with both styling and scripting.

Sharing Is Caring:

Leave a Comment