javascriptinnerhtmlgetelementbyid

How to change HTML Div content when button in clicked using Javascript?


I want to let the user click a button that will change the contents of the div. I'm creating a football lineup with each button representing a formation and when they click the button, the contents of the div will change to represent the formation of the lineup. This is what the page looks like before the button is clicked This is what I want the page to look like after the user clicks the 4-3-3 button

I tried to do this to check if the basics would work:

    const changeText = () => {
        document.getElementsById("changer").innerHTML = "you clicked me"
      }
    <button onClick={changeText()}>4-3-3</button>
    <div ref={contentRef} className="col-9" id="changer">
                <SoccerLineUp
                  size={"fill"} //responsive
                  color={"green"}
                  pattern={"lines"}
                  homeTeam={homeTeam}
                />
              </div>

However, the page was blank when I did this.

Here is my complete code for reference:

export default function App() {
  const [state, setState] = useState({
    color: "588f58",
    pattern: "lines",
    showHomeTeam: false, //idk what this does
    homeTeamColor: "f08080",
    homeTeamNumberColor: "ffffff",
    homeGoalkeeperColor: "d6cb65",
    homeGoalkeeperNumberColor: "333333",
    nameColor: "ffffff"
  });

  const [error, setError] = useState(null);
  const [homeTeam, setHomeTeam] = useState(
    localStorage.getItem("homeTeam") === null
      ? {
        squad: {
          gk: null,
          df: [],
          cdm: [],
          cm: [],
          cam: [],
          fw: []
        },
        style: {
          color: `#${state.homeTeamColor}`,
          numberColor: `#${state.homeTeamNumberColor}`,
          nameColor: `#${state.nameColor}`
        }
      }
      : JSON.parse(localStorage.getItem("homeTeam"))
  );

  const [number, setNumber] = useState(1);
  const [playerName, setPlayerName] = useState("");
  const [playerTeam, setPlayerTeam] = useState("homeTeam");
  const [playerPosition, setPlayerPosition] = useState("gk"); //why?

  const handlePlayerNameChange = (event) => {
    setPlayerName(event.target.value);
  };

  const handlePlayerPositionChange = (event) => {
    setPlayerPosition(event.target.value);
  };

  const removePlayer = (team, position, id) => {
    if (position === "gk") {
      setHomeTeam((homeTeam) => ({
        ...homeTeam,
        squad: { ...homeTeam.squad, gk: null }
      }));
    } else if (position === "df") {
      setHomeTeam((homeTeam) => ({
        ...homeTeam,
        squad: {
          ...homeTeam.squad,
          df: homeTeam.squad.df.filter((player) => player.id !== id)
        }
      }));
  };

  const addPlayer = () => {
    setError(null);
    if (playerName === "") {
      setError("Player Name required!");
    }
    else if (1 + homeTeam.squad.df.length + homeTeam.squad.cdm.length >= 11) {
      setError("Squad is full!");
    }
    else {
      let playerObj = {
        id: nanoid(),
        number: number,
        name: playerName,
        color: `#${state.homeTeamColor}`,
        numberColor: `#${state.homeTeamNumberColor}`,
        namecolor: `#${state.nameColor}`
      };
      if (playerPosition === "gk") {
        if (homeTeam.squad.gk !== null) {
          setError("goal keeper is full!");
        } else {
          playerObj.onClick = () =>
            removePlayer("homeTeam", "gk", playerObj.id);
          setHomeTeam((homeTeam) => ({
            ...homeTeam,
            squad: { ...homeTeam.squad, gk: playerObj }
          }));
        }
      } else if (playerPosition === "df") {
        if (homeTeam.squad.df.length === 5) {
          setError("defence is full!");
        } else {
          playerObj.onClick = () =>
            removePlayer("homeTeam", "df", playerObj.id);
          setHomeTeam((homeTeam) => ({
            ...homeTeam,
            squad: {
              ...homeTeam.squad,
              df: [...homeTeam.squad.df, playerObj]
            }
          }));
        }
      }
    }
    setNumber(number + 1);
  };

  const changeText = () => {
    document.getElementsByClassName("changer").innerHTML = "you clicked me"
  }

  return (
    <>
      <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
          <div className="logoHeader">
            <button className="navButton">DreamElevenBuilder</button>
          </div>
          <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <ul>
              <li><a className="socialIcons" href="a" <FontAwesomeIcon icon={fa} /></a></li>
            </ul>
          </div>
        </div>
      </nav>

      <div className="containerFluid" >
        <div className="row">
          <div className="col-2">
            <form className="userForm">
              <div className="formRow">
                <div className="formError">
                  {error !== null ? (
                    <div
                      className="alert alert-danger p-2 m-0"
                      role="alert"
                    >
                      {error}
                    </div>
                  ) : null}
                </div>
                <div>
                  <label htmlFor="playerName"><b>Player Name</b></label>
                  <input
                    type="text"
                    className="form-control"
                    id="playerName"
                    placeholder="Player Name"
                    value={playerName}
                    onChange={handlePlayerNameChange}
                  />
                </div>
                <fieldset>
                  <div>
                    <label className="col-form-label">
                      <b>Player Position</b>
                    </label>
                    <div>
                      <button onClick={changeText()}>4-3-3</button>
                      <div className="form-check">
                        <input
                          className="form-check-input"
                          type="radio"
                          value="df"
                          id="df"
                          checked={playerPosition === "df"}
                          onChange={handlePlayerPositionChange}
                        />
                        <label className="form-check-label" htmlFor="gridRadios1" for="df">
                          Defence
                        </label>
                      </div>
                    </div>
                  </div>
                </fieldset>
              </div>
            </form>
            <div className="buttonPosition">
              <button className="addButton" onClick={addPlayer}>
                Add Player
              </button>
            </div>
            <hr />
          </div>
          <div ref={contentRef} className="col-9" id="changer"> 
                //THIS IS THE DIV I WANT TO CHANGE WHEN THE USER CLICKS THE BUTTON.
            <SoccerLineUp
              size={"fill"} 
              color={"green"}
              pattern={"lines"}
              homeTeam={homeTeam}
            />
          </div>
        </div>

I hardcoded the values to get the formation. I was wondering if this would go inside the innerHTML to make it work? Values hardcoded for the 4-3-3 formation


Solution

  • Your code has 2 issues:

    1. You are using document.getElementsById instead of document.getElementById.
    2. In the button's on click event, you are directly calling the changeText

    Here's what you can do:

    const changeText = () => {
        document.getElementById("changer").innerHTML = "you clicked me";
    }
    
    <button onClick={changeText}>4-3-3</button>
    <div ref={contentRef} className="col-9" id="changer">
        <SoccerLineUp
            size={"fill"} //responsive
            color={"green"}
            pattern={"lines"}
            homeTeam={homeTeam}
        />
    </div>
    

    Also I'd recommend using .innerText if you want to change the text to something generated by the user or sanitise the text for better security. Hope this helps.