Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set element ID on page load with Jquery?

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!

like image 280
Nấm Lùn Avatar asked Jan 25 '26 05:01

Nấm Lùn


1 Answers

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

like image 135
Gautam3164 Avatar answered Jan 28 '26 05:01

Gautam3164



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!