简体   繁体   中英

class (Object) vs id

During the web development i encountered with many problems and resolved it but these problems gave me a thought which i want to share and would like to know your view.

Which One is efficient Class Or ID : Both has own specification but i think Class is more convenient over ID (if you are dealing with thousands of IDs.) I know Id is quite efficient for DOM Traversing but what if you have hundreds of elements with IDs, How do you manage?

Using CLASS: One class can be derived by many elements and the individual elements can be dealt by using "this" object .

I am curious to know your view OR how do you handle the project/projects when you have many-many elements with ID or Class name

<div class="example" onclick="function click(this);"> </div>  
<div class="example" onclick="function click(this);"> </div> 
<div class="example" onclick="function click(this);"> </div>


    function click(obj){
        alert(obj.classname + "We can access any individual element by using Object");   
       }

<div id="exm_1"> </div> 
<div id="exm_2"> </div> 
<div id="exm_3"> </div> 

but in case of ID, we go through each ID

I liked a few guidelines that are put together by one of my managers, I would like to mention them here:

Start with the following common sense guidelines, and apply them to both JavaScript selectors and CSS selectors.

Use an ID if:

  • You are certain that the element only appears once in the whole page.
  • The desired style or JS behavior is specific to only one area of the whole page.

Typical ID Examples:

  • Large container divs for entire sections of the page ("#interior", "#global-status", "#tree-container")
  • Links or buttons with special names and purposes ("#add-new-report", "#preview-popup")

Use a class if:

  • It is possible for the element to appear multiple times in the same document.
  • The desired style or JS behavior is general and is applicable to multiple elements.

Typical Class Examples:

  • Reusable interface patterns (".action-links", ".title-bar", ".h1-with-border")
  • Element states (".current-selected", ".highlighted")

You should follow this general guidelines:

2) Use a class when you need many elements to share some common behaviour, or when there's currently only one element but you're not sure if there will be more with the same behaviour in the future.

1) Use an Id when an element needs unique identification and you're sure there will be only one with it (think in the future code changes). There should never, never be 2 or more elements with the same id.

Hope this helps. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM