In web development, selectors are used to identify specific elements on the page so that they can be targeted with styles or manipulated with JavaScript. Selectors can be based on element type, class, or ID.
For example, consider the following HTML code:
<h1 class="main-title">Welcome to my webpage</h1>
<p id="intro">This is the introduction paragraph</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
In this example, you could use the following selectors:
-
h1
to target allh1
elements on the page -
.main-title
to target all elements with the classmain-title
-
#intro
to target the element with the IDintro
Selectors are often used in conjunction with CSS stylesheets to apply styles to specific elements on the page. For example, you might use the .main-title
selector to apply a specific font size and color to all elements with the main-title
class.
Selectors can also be used with JavaScript to manipulate elements on the page. For example, you might use a selector to change the text of an element, hide it, or add a new element to the page.