Using classes and IDs for styling and scripting : Module 2 Lesson 3

 Classes and IDs are essential attributes in HTML for applying styles and scripting to elements on a web page. They provide a way to uniquely identify or group elements, allowing for targeted styling with CSS and selective manipulation with JavaScript. In this article, we'll explore how to use classes and IDs effectively, along with code examples and corresponding outputs.

Understanding Classes and IDs

  • Classes: Classes are used to group multiple elements that share the same styling or behavior. A class can be applied to multiple elements, and an element can have multiple classes.
  • IDs: IDs are used to uniquely identify a specific element on a web page. Each ID must be unique within the document and can only be applied to one element.

Using Classes for Styling

Classes are commonly used to apply CSS styles to multiple elements that share common characteristics. Here's an example of how to use classes for styling:

html
<!DOCTYPE html> <html> <head> <style> .red-text { color: red; } .bold-text { font-weight: bold; } </style> </head> <body> <p class="red-text">This text is red.</p> <p class="bold-text">This text is bold.</p> <p class="red-text bold-text">This text is both red and bold.</p> </body> </html>

Output:

scss
This text is red. This text is bold. This text is both red and bold.

Using IDs for Scripting

IDs are often used to target specific elements for scripting purposes, such as adding interactivity or dynamically updating content. Here's an example of how to use IDs for scripting with JavaScript:

html
<!DOCTYPE html> <html> <head> <script> function changeText() { document.getElementById("demo").innerHTML = "New text!"; } </script> </head> <body> <p id="demo">This is a paragraph.</p> <button onclick="changeText()">Click me to change text</button> </body> </html>

Output:

vbnet
This is a paragraph. [Click me to change text]

Conclusion

Classes and IDs are powerful attributes in HTML that enable targeted styling and scripting on web pages. Classes allow for the application of common styles to multiple elements, while IDs provide a way to uniquely identify specific elements for scripting purposes. By understanding how to use classes and IDs effectively, you can create visually appealing and interactive web pages with ease

Previous Post Next Post