lmgguy
lmgguy

Reputation: 89

How to assign an id to an HTML <li> element using javascript?

I have an <li> element that needs to be assigned an id="onlink" attribute when the user clicks on the specific <li> . How to do it using Javascript?

Upvotes: 1

Views: 5083

Answers (3)

$('#pages li').each(function(i) {
    $(this).attr('id', 'onlink'+(i+1));
});
#onlink1{
color:green;
}

#onlink2{
color:red;
}

#onlink3{
color:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="pages">
    <li class="something"><a href="#"></a> 1</li>
    <li class="something"><a href="#"></a> 2 </li>
    <li class="something"><a href="#"></a> 3 </li>
</ul>

Upvotes: 1

Koby Douek
Koby Douek

Reputation: 16675

You can set the id property of an element by using element.id='newid';

in your case:

<script>
    function changeID(obj) {
        obj.id = 'onlink';
    }
</script>

<li onclick='changeID(this);'>text</li>

Upvotes: 2

Nihal
Nihal

Reputation: 5334

try this:

<!DOCTYPE html>
    <html>
    <head>
    <style>
    #text{
    font-size:40px;
    }
    </style>
    </head>
    <body>


    <li>
    I am a LI element
    </li>

    <button onclick="myFunction()">Try it</button>

    <script>
    function myFunction() {
        var x = document.getElementsByTagName("LI")[0];
        x.setAttribute("id", "text");
    }
    </script>

    </body>
    </html>

Upvotes: 0

Related Questions