-2

HTML (I'm writing in a combination of Markdown & HTML).

    - Ex. **<a class="kanji">犬</a>が**好き ・ I like dogs.
    - Ex. **<a class="kanji">私</a>は**オーケーです・**I am** okay

JavaScript

const kanjiAnchor = document.getElementsByClassName("kanji")

for (var i = 0; i < kanjiAnchor.length; i++) {
  kanjiAnchor[i].href = `https://jisho.org/search/${kanjiAnchor.textContent}`
  kanjiAnchor[i].target = "_blank"
}

The above code returns an href of "https://jisho.org/search/undefined". I was able to do this on a smaller scale only selecting a single anchor with `document.getElementById("kanji"), but I want this to be done to every anchor tag with the class "kanji".

  • `kanjiAnchor` is a collection, not a single element. It does not have a `.textContent` property. You need to access the index you're iterating over. – CertainPerformance Dec 24 '22 at 02:47
  • It’s basically a typo. You forgot an `[i]`. Consider not misnaming your variables. `kanjiAnchor` is wrong: it’s not _one_ anchor. Consider using better alternatives to `for` loops. The entire JS code can be replaced by `Array.from(document.querySelectorAll(".kanji")).forEach((kanjiAnchor) => { kanjiAnchor.href = new URL(kanjiAnchor.textContent, "https://jisho.org/search/"); kanjiAnchor.target = "_blank"; });`. – Sebastian Simon Dec 24 '22 at 02:47

1 Answers1

0

You need to access the textContent of the current element rather than the collection of elements.

kanjiAnchor[i].href = `https://jisho.org/search/${kanjiAnchor[i].textContent}`
Unmitigated
  • 76,500
  • 11
  • 62
  • 80