Set element ID on page load with Jquery?

3.4k views Asked by At

Assume that I have some HTML elements like these:

<div id="wrapper">
    <ul>
        <li><a>Parent 1</a>
            <ul>
                 <li><a>Child 1</a></li>
                 <li><a>Child 2</a></li>
                 <li><a>Child 3</a></li>
            </ul>
        </li>
        <li><a>Parent 2</a>
            <ul>
                 <li><a>Child 1</a></li>
                 <li><a>Child 2</a></li>
                 <li><a>Child 3</a></li>
            </ul>
        </li>
    </ul>
</div>

How can I set the ID for the first UL element in the #wrapper when $(document) ready??

Thanks in advance!

4

There are 4 answers

0
GautamD31 On BEST ANSWER

Try with :first like

$('#wrapper ul:first').attr('id', 'customeId');

Or you can try with :eq(0) like

$('#wrapper ul:eq(0)').attr('id', 'customeId');

Even(May be) you can try with .eq(0) like

$('#wrapper ul').eq(0).attr('id', 'customeId');

Make sure that you have this script on DOM ready like

$(document).ready(function(){
    $('#wrapper ul:first').attr('id', 'customeId');
});

And please correct your html because it is breaking while closing ul

0
Adil On

Like this.

Live Demo

$(document).ready(function(){
    $('#wrapper ul:first').attr('id', 'yourid');
});

You have invalid html as well, you missed the closing ul

<div id="wrapper">
    <ul>
        <li><a>Parent 1</a>
            <ul>
                 <li><a>Child 1</a></li>
                 <li><a>Child 2</a></li>
                 <li><a>Child 3</a></li>
            </ul>    
        </li>
        <li><a>Parent 2</a>
            <ul>
                 <li><a>Child 1</a></li>
                 <li><a>Child 2</a></li>
                 <li><a>Child 3</a></li>
            </ul>     
        </li>
    </ul>
</div>
0
Anoop Joshi P On
   $(document).ready(function () {
    $("#wrapper").children("ul").attr("id", "myid");
   });
0
Prateek On

Use .attr

$("#wrapper ul:first").attr("id","id");