Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Select multiple elements with same ID using JQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 18.5k
    Comment on it

    ID's in HTML are generally used as unique identifiers for the elements present in the DOM but it is not a compulsion to have only one element with a unique ID, which means you can have multiple elements with the same ID.

    JQuery selector $("#idofelement") finds the first matching element with the ID but what to do if you need to apply a style to all the elements with the same ID.

    Here is a solution: You can use JQuery selector $("[id='idofelement']") to select all the elements with matching ID.

    Lets look at an example:

    HTML CODE:

    <div id="id1"></div>
    <div id="id2"></div>
    <div id="id1"></div>
    <div id="id2"></div>
    <div id="id1"></div>
    <div id="id2"></div>
    <div id="id1"></div>
    <div id="id2"></div>
    

    CSS CODE:

    #id1{display: block; width:100px;height:100px;}
    #id2{display: block; width:100px;height:100px;}
    

    JAVASCRIPT CODE:

    $(function(){
    $("[id='id1']").css({"background-color":"red"});
    $("[id='id2']").css({"background-color":"green"});
    });
    

    This code would change background color of all the elements with id1 to red and id2 to green. To see the working example Click Here

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: