简体   繁体   中英

Apply id to list item link using jQuery

I want to add an id to a unordered list item. Not to the <li> tag, but inside the <li> tag, like so:

<li><a href="#" id="Here i want to add an id"></a></li>

So if you can see, inside the a tag, I want to add an ID.

$('li > a').attr('id', 'id_to_add');

Ideally you'll have a more specific selector for that li . You should give your li a class or id that you can use to better-identify it, eg

<li class="needs-id">...

$('li.needs-id > a').attr('id', '...');

You will need to make sure you don't introduce duplicate id's into your document. As such you will need to test if an id is already used in the document. Using attr('id', 'some_id') on a set of nodes, will directly introduce duplicates. As such, you will have to do some iterations using .each . Also you need to make sure that you don't accidentally remove existing id's, which could cause unwanted side effects.

function generateId(base) {
    generateId.iterator = generateId.iterator || 1;
    base = base || '';
    while (document.getElementById(base + generateId.iterator)) {
       generateId.iterator ++;
    }
    return base + generateId.iterator;
}

$('li > a').each(function() {
    this.id = this.id || generateId();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM