ID SELECTORS AND CLASS SELECTORS



Class and id selectors are commonly used in CSS selectors. This article shows the usage of both the selectors and its significance.




In a web page there may be many html elements used like menu, article, paragraph, image, sliders. For any elements class or id name can be assigned.  

Id selectors are defined as unique identification of the element and can be used only once in the page. Class selectors are used when you consistently style multiple elements of a page. Classes are used when more elements share the same style. Id selectors are used for unique purposes like main header or footer of the page.

Let,
<p class =”class_one”>This is a paragraph</p>
<p id=”id_one”> This is a paragraph </p>

The styles for the class or id can be styled through CSS or JS through HTML DOM. When a class is styled through CSS it uses the prefix period (fullstop) whereas an id uses the prefix hash(#).

Naming of class and id selectors are left to our choice. No particular name has any effect to the element in general.

.class_one
{
            color: #eeeeee;
}
#id_one
{
            color: #565759;
            font-weight:bold;
}

Each element can have multiple classes associated with it however it is not the case with id selectors. Also each element can have both the class selectors and id selectors like:
<p class= ” class_one   class_two ”  id = ” id_one ”> This is a paragraph. </p>


With respect to cascading rules, there may be conflicts with one declaration and the other. During these times id selectors have more specificity when compared to class selectors.


With respect to JavaScript using id and class may be judicial. JavaScript depends on id selectors for being dependable on the function getElementById. If id elements are used it is easy to manipulate the values for adding and removing elements in the page.


With respect to performance, Id selectors are tend to be faster than class selectors as the DOM need not traverse the entire document going through all the elements.









Comments

Popular posts from this blog

What are some mistakes people make when they start learning HTML, CSS and JavaScript?

How to initialize Datatable plugin?

Datatables.net - Plugin options