JJJollyjim
JJJollyjim

Reputation: 6227

Adding # before a div id without creating an HTMLDivElement

I have an array of div names (with no hash), and i'm using the following jQuery code do do something with them:

for(dayList in dayLists) {
  dayListID = "#" + dayList;
  $(dayListID).append("test");
}

Unfortunately, it does not work. I can see in the console that dayListID is an "HTMLDivElement", rather than the string that JQ is expecting. How can I join a hash and the div name while keeping the result as a string? Thanks!

Upvotes: 1

Views: 168

Answers (3)

kubetz
kubetz

Reputation: 8566

Try this:

for(dayList in dayLists) {
  dayListID = "#" + dayLists[dayList];
  $(dayListID).append("test");
}

dayList in for .. in is not a i-th value of the dayLists, but it is the index. So for array ["one", "two"] variable dayList is 0, 1 and to get the values you must use dayLists[dayList].

As Matt wrote in the comments it is good to use hasOwnProperty to make sure the properties we are looping through are the objects own.

for(dayList in dayLists) {
  if(dayLists.hasOwnProperty(dayList) {
    dayListID = "#" + dayLists[dayList];
    $(dayListID).append("test");
  }
}

... and then you realize the standard simple for loop (answer by MДΓΓ БДLL) is actually a better idea. The standard for is also faster.

See details HERE.

Upvotes: 2

vdbuilder
vdbuilder

Reputation: 12974

You should be using this:

dayLists = ["something", "somethingElse"];
for(var i=0; i<dayLists.length; i++){
    $("#" + dayList[i]).append("test");
}

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359966

Don't use a for...in loop to iterate over arrays. Use a regular ol' for loop:

for(var i=0; i<dayLists.length; i++) {
  dayListID = "#" + dayLists[i];
  $(dayListID).append("test");
}

See for yourself what the difference is: http://jsfiddle.net/mattball/h9hpr/

Upvotes: 6

Related Questions