Try to search your question here, if you can't find : Ask Any Question Now ?

Is there reason bracket operators [] might not work with getElementsById() within a react component?

HomeCategory: stackoverflowIs there reason bracket operators [] might not work with getElementsById() within a react component?
Avatarpushpa asked 4 months ago

I’m building a small react app containing a list of many programming languages with courses. Each list element will contain a background image provided by one “sprite” png image of their corresponding logo. Instead of giving each div an id to then add a background image and set the position of the image, I gave all of them the class languages for which I will set the background url() quickly then position after.

I’ve tried to directly set the languages class’s background url from my external style-sheet but the link wont reach my public/images folder for some reason when It gets built with webpack. I’ve decided to settle with linking it with my component file instead.

The issue I’m coming across is when I try to set
const languageElements = document.getElementsByClassName("languages");

When calling console.log(languageElements), I see that it returns an HTMLCollection[] array for which I can see my elements clearly.

However, when I call console.log(languageElements[0]) it surprisingly returns undefined.

Am I missing something here? Does this something that has to do with react?

import React, { Component } from "react";
import "../styles/Center.scss";

class Center extends Component {
  constructor(props) {

  componentDidMount() {
    console.log("Center Mounted Successfully.");

  render() {
    const languageElements = document.getElementsByClassName("languages");
    languageElements[0].style.background = "url(../images/full-languages.png)";

    return (
              CS1022: <span className="languages cpp" />
              <span className="languages c" />
              <span className="languages cpp" />
              <span className="languages html" />
              <span className="languages css" />
              <span className="languages js" />
              CS2350: <span className="languages java" />
              CS2420: <span className="languages java" />
              CS2550: <span className="languages sql" />
export default Center;

I expect the use of the bracket operators to allow me to access each element within the HTMLCollection[] getElementsById() returns.

1 Answers
Best Answer
AvatarArben answered 4 months ago
Your Answer

15 + 17 =

Popular Tags

WP Facebook Auto Publish Powered By :