My code is behaving strangely. Indeed, I created my data in a JSON object:
injectJson = {
"title": "Questions for a champion",
"rules": [
{
"idChrono": "chrono-minute",
"text": "Top is gone!",
"tag": [
{
"id": "chronometer",
"text": "countDown"
}
]
}
]
}
Here is my HTML code:
<div id="rules">
<h3>The game's rules!</h3>
</div>
<div id="begin">
<a href="#" class="link">Begin</a>
</div>
And here is the Javascript code with which I inject the HTML code:
selectLinkBegin = document.getElementById("begin");
selectLinkBegin.firstElementChild.addEventListener("click", function(injectJson) {
// Injection code
selectRules = document.getElementById("rules");;
selectRules.firstElementChild.innerText = injectJson.rules[0].texte;
});
In my computer,the JSON object and the JavaScript code are in the same .js file. I load my script at the end of the body tag. When I open my .html code in the browser, the console displays:
Uncaught TypeError: Cannot read property '0' of undefined at HTMLAnchorElement.
But when I copy the Javascript code into the console, I get the expected result: h3's text content is updated.
Demo:
injectJson = {
"title": "Questions for a champion",
"rules": [{
"idChrono": "chrono-minute",
"text": "Top is gone!",
"tag": [{
"id": "chronometer",
"text": "countDown"
}
]
}]
}
selectLinkBegin = document.getElementById("begin");
selectLinkBegin.firstElementChild.addEventListener("click", function(injectJson) {
// Injection code
selectRules = document.getElementById("rules");;
selectRules.firstElementChild.innerText = injectJson.rules[0].texte;
});
<div id="rules">
<h3>The game's rules!</h3>
</div>
<div id="begin">
<a href="#" class="link">Begin</a>
</div>
Can you explain to me what is going on? How to remedy this? I have already emptied my cache but it's still the same.
injectJsonparameter from your click handler, and usetextproperty instead oftexte.