0

For my school's website they have a dropdown list of courses that you're currently enrolled in on the home page. However, if you see it, it is cluttered full of letters that many people might not want to see.

I already know how I'm going to do this. I'm going to use jQuery to select each list item:

var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");

This returns an array of <a> elements in text form.

Using links.text("Boo!"); I can set the text of all of them to "Boo!", but I want to change each one individually, using a for/in loop to itterate through each <a> and change the text depending on what the value of the href is.

However, whenever I do this, since the items in the array are strings, I cannot do anything to them with jQuery.

Any help with this is appreciated :)

Here's my code so far (running from a $.getScript() from a JS bookmarklet):

var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
//links.text("Boo!");

var count = 1;
for (var link in links) {
    link.text("Boo #" + count);
    count += 1;
}

Relevant markup: http://hastebin.com/ulijefiqaz.scala

5
  • include all relevant code to OP Commented Oct 7, 2016 at 2:49
  • Two things-- the relevant markup would be helpful as well. Also: for...in loops should really only be used to iterate over keys in an object. If you are iterating over an array, you should really be using a standard for loop. Also, since it's an array, you could also just use forEach... Commented Oct 7, 2016 at 2:56
  • @anied I'm used to using python's for/in loops so that didn't really occur to me. What would the benefits be of using forEach over for/in? Also I added a hastebin link to the relevant markup. Commented Oct 7, 2016 at 3:00
  • @RedXTech - forEach is a syntax some people prefer as it allows you to use a function (although it is difficult/impossible to break; from. But more importantly, you should not use for...in loops to iterate over an array-- it can yield problematic results... Commented Oct 7, 2016 at 3:04
  • @anied ah ok, thanks :) Commented Oct 7, 2016 at 3:07

1 Answer 1

1

You can use the jQuery .each iterator function.

var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");

var count = 1;

links.each(function() {
    $(this).text("Boo #" + count++);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Basic tests have worked so far, will accept once I test the main features :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.