mercredi 9 septembre 2020

Selecting a P inside a DIV gives error in browser console but in JsFiddle works fine. Why?

I'm creating a small thing for practice with JavaScript and I get an error which I can't understand why is happening. The browser (chrome, firefox) gives me the following error message in the console: "Uncaught TypeError: Cannot read property 'getElementsByTagName' of null at script.js:12", but when I try the code in JSFiddle everything is working as expected. JavaScript is allowed in the browser, so normally it should work fine.

The other question is: How can I avoid typing so many if's? If I want to use a JavaScript switch, how should I write it?

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/en/";
console.log(findUrl);

if (findUrl.match(/en/)) {
  console.log("The match has been found!");
  //select the paragraph inside the div with id #texts
  let findP = document.getElementById("texts").getElementsByTagName("p");
  //define a variable with the new text
  let newtxtEN = "A very long text in English to replace the lorem ipsum";
  //replace the lorem ipsum text
  findP[0].innerText = newtxtEN;
}

if(findUrl.match(/fr/)) {
   console.log("The match has been found!");
  //select the paragraph inside the div with id #texts
  let findP = document.getElementById("texts").getElementsByTagName("p");
  //define a variable with the new text
  let newtxtFR = "Je ne parle pas français";
  //replace the lorem ipsum text
  findP[0].innerText = newtxtFR;
}

if(findUrl.match(/de/)) {
   console.log("The match has been found!");
  //select the paragraph inside the div with id #texts
  let findP = document.getElementById("texts").getElementsByTagName("p");
  //define a variable with the new text
  let newtxtDE = "Ich bin kein Deutscher";
  //replace the lorem ipsum text
  findP[0].innerText = newtxtDE;
}
#texts {
  border: 1px solid black;
  margin: 5px;
  padding: 5px;
  color: blue;
}
p {
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
}
<div id="texts">
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit.
    Ut,consequuntur.
  </p>
</div>

Aucun commentaire:

Enregistrer un commentaire