'How to resolve "Did you set the Font Awesome icon font size inside the body of function?" error?
Can someone please tell me why, when I test the code, I get an error that the code has failed even though everything is working properly? I get the same error for all the 4 functions, and the font size is entered. Thanks in advance.
The Error: Did you set the ingredients Font Awesome icon font size inside the body of the ingredientsNormal() function?
<script>
function ingredientsHover() {
document.getElementById("ingredients").firstElementChild.firstElementChild.style.fontSize = "300%";
}
function ingredientsNormal() {
document.getElementById("ingredients").firstElementChild.firstElementChild.style.fontSize = "100%";
}
function preparationHover() {
document.getElementById("preparation").firstElementChild.firstElementChild.style.fontSize = "300%";
}
function preparationNormal() {
document.getElementById("preparation").firstElementChild.firstElementChild.style.fontSize = "100%";
}
</script>
Solution 1:[1]
Could you tell is why the code has failed? What kind of information did you get from the notification?
The browser behaves permissive regarding not correct executed code. He tries doing it's best converting your stuff into usable HTML ^^ That's way you're test may fail but your browser silently accepts it.
My first approach would be to reduce the complexity by only executing one of those functions first and secondly only logging the outcome of a reduced function call like:
function ingredientsHover() {
const ingredients = document.getElementById("ingredients").firstElementChild;
console.log("ingredients: ", ingredients);
}
If this works you can expand your approach until you hopefully catch the problematic part.
By the way... Selecting elements the way you're doing it is error prone.
You have several ways to improve your code regarding this. Two possible suggestions:
- Make use of optional chaining like:
document.getElementById("ingredients")?.firstElementChild?.firstElementChild?.style?.fontSize="300%" - Improve your way of selecting elements like the following psydo code proposes a possible way:
document.querySelector('#ingredients:first-child:first-child');I didn't tested it but you should get the idea right? :-)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
