0

I need help finding an element with a specific class name and then replace it with a new class name. Here is the code I came up with. I get no results. The class name does not change, and there are no errors in the console.

Updated Code:

var classMatches = document.querySelectorAll(".crux.attachFlash");
for (var i = 0; i < classMatches.length; i++) {
    classMatches[i].className = " ";
}
1
  • 1
    You're looping but never using the i to actually access an individual element of the collection. Commented Jun 5, 2012 at 22:20

1 Answer 1

3

Because you need to amend the class-name of the matched element, not the array of elements:

var classMatches = document.querySelectorAll(".crux.attachFlash");
for (var i = 0; i < classMatches.length; i++) {
    classMatches[i].className = " ";
}

You forgot the [i] index, so you were trying to set the className for whole array (Which, as you've found, does not work).

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

2 Comments

Ah! thank you so much that clears it up :) Oh if I could ask about one more thing. If i wanted to use getElementsByClassName instead of querySelectorAll could you show me how?
As far as I'm aware there's no difference; just substitute getElementsByClassName() for querySelectorAll().

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.