Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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>
   $(document).ready(function () {
    $("#wrapper").children("ul").attr("id", "myid");
   });

Use .attr

$("#wrapper ul:first").attr("id","id");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top