0

I am trying to learn how to use for loop to create and assign variables. I have a list of items gathered using:

document.getElementsByClassName("category-item-link")

it returns:

[a.category-item-link, a.category-item-link, a.category-item-link, a.category-item-link, a.category-item-link, a.category-item-link]

My goal is to assign each item to a variable called link[0] - link[5] using for loop.

1
  • 3
    getElementsByClassName already returns a collection of elements. var link = document.getElementsByClassName("category-item-link")? Commented Mar 21, 2019 at 6:11

2 Answers 2

1

Since it already returns a collection of elements, you can just do this (I converted link into an array so you can see just the elements):

var link = [...document.getElementsByClassName("category-item-link")];
console.log(link);
<a class="category-item-link">Link</a>
<a class="category-item-link">Link</a>
<a class="category-item-link">Link</a>
<a class="category-item-link">Link</a>
<a class="category-item-link">Link</a>
<a class="category-item-link">Link</a>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the input!
0

getElementsByClassName returns an object with the collection of elements. So you can already access each item to a variable called link[0] - link[5] by this:

const link = document.getElementsByClassName("category-item-link")

However, for practicing for loop, you may do this:

const objs = document.getElementsByClassName("category-item-link")
const link = []

for (let i = 0; i < objs.length; i++) {
    link[i] = objs[i]
}

or like this:

const objs = document.getElementsByClassName("category-item-link")
const link = []

for (const obj of objs) {
    link.push(obj)
}

1 Comment

Thank you for providing this explanation. I did not know that I had to create an empty list before the for loop: const link = [] Also in the for loop, I kept putting var in front and getting "Uncaught SyntaxError: Unexpected token [". Still new to coding itself and just wondering why I shouldn't have var. for (let i = 0; i < objs.length; i++) { var link[i] = objs[i] }

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.