0

let's say I have my HTML document like

<a href='#' class='class_1'>Content</a>
<a href='#' class='class_2'>Content</a>
<a href='#' class='class_3'>Content</a>
<a href='#' class='class_4'>Content</a>
<a href='#' class='class_5'>Content</a>

Now, I have selected those anchor tags with querySelectorAll and looped through them using forEach.

Inside forEach, after calculating some stuff, I need to apply a style to a specific anchor tag with its class.

anchorList.forEach(link => {})

How can I select that link with a certain class without using another loop?

Question might be little unclear, feel free to ask anything needed

1 Answers1

1

Since you are already looping through all of the anchor tags using a forEach, you can check for the specific class in the loop itself. Try this code:

var anchorList = document.querySelector("a");

anchorList.forEach(link => {
  // calculations...
  if(link.className === "class_1"){
    link.style.color = "red"; // or anything else
  }
  // continue calculations...
});

Don't hesitate to comment if something is incorrect or not what you were asking for, I'll update my answer.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
  • `if(link.classList.contains("class_1")` https://stackoverflow.com/a/16337545/6127393 – Arleigh Hix Jul 17 '22 at 16:26
  • @ArleighHix: That's another method, I just decided to use the direct `className` because the HTML was already given. Otherwise, that would be a more general solution and would be preferred. – Lakshya Raj Jul 17 '22 at 16:38
  • I actually tried using `if (link.classList.contains('class'))` but it didn't work as expected so I had to use another for loop to check for the condition. I don't want to use another for-loop since I am already looping. – Lifeless Programmer Jul 19 '22 at 08:06
  • @LifelessProgrammer: Make sure when you use the `contains` method you pass in one of the actual classes. `class` is not one of the classes in your HTML (AFAIK, anyways). I think the correct statement is `if (link.classList.contains("class_1"))` – Lakshya Raj Jul 19 '22 at 15:13
  • @LakshyaRaj Thanks but in the above statement `if (link.classList.contains('class'))` `class` is just a placeholder for `class_1` or other classnames. – Lifeless Programmer Jul 19 '22 at 17:32
  • @LifelessProgrammer: If that's the case... then the problem might be something else. Maybe you can send the full code of the problem (on GitHub or JSFiddle?) so we can investigate further. From what I know, that code should be working *pretty* well. – Lakshya Raj Jul 19 '22 at 18:57