tmnsnmt
tmnsnmt

Reputation: 95

How to find all links in a ul and give them ids

Say I have an unordered list such as:

<ul class="mylist">
<li><a href="">link 1</a></li>
<li><a href="">link 2</a></li>
</ul>

How would I iterate through this list, taking the link text and making it the ID of itself? (I'm guessing I'd have to remove spaces as well if the link text had them before making it usable as an ID)

I have tried just selecting the link and giving it an ID to get myself started but can't get that alone to work. I tried to give the first link an ID:

$('.mylist > li > a').eq(0).attr('id', 'link1');

Upvotes: 0

Views: 337

Answers (4)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

You can try something like this.

$('.mylist > li > a').each(function(){
   $(this).attr('id', $(this).text().replace(/ /g, ''));
});

Use $.each() to loop through a inside .mylist and set their id's using .attr() and make sure all the anchor text must be unique otherwise id's will repeat and results in invalid html.

Upvotes: 2

PriVictor
PriVictor

Reputation: 49

var link1 = $('.mylist li:nth-child(1)').attr('href');

var link2 = $('.mylist li:nth-child(2)').attr('href');

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You can do,

$(".mylist li a").each(function() {
  $(this).attr("id", $(this).text().replace(/ /g, ''));
});

Loop through each anchor element using $().each loop, then change its id using attr() method. Note that, id should not contains whitespaces in it.

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

You could set property (which is mapped to attribute in this case) or attribute (use attr instead of prop method), see e.g:

$(".mylist li a").prop('id', function(){
    return this.innerHTML.trim().replace(/ /g,'');
});

But you need to be sure each anchor text is unique to avoid any duplicate IDs...

Otherwise, you can use:

$(".mylist li a").prop('id', function(i){
    return this.innerHTML.trim().replace(/ /g,'') + "_" + i;
});

Upvotes: 1

Related Questions