I’m quite new to javascript and have been searching for a solution with no joy.
I want to switch the content of a certain p tag depending on if the H1 tag contains certain text. I aim to put this js in the of every page ready for when it’s needed.
I have figured out that ‘if’ and ‘else if’ should be a suitable way of doing it, but I would be open to other ideas. I have tried writing a ‘switch’ statement but I couldn’t figure out how to get it working.
So far the closest I have found is..
<h1>This is about Red</h1> <p id="colour"></p> <script> if('h1:contains("Red")'){ document.getElementById("colour").innerHTML = "Red description"; } else if ('h1:contains("Orange")'){ document.getElementById("colour").innerHTML = "Orange description"; } else if ('h1:contains("Green")'){ document.getElementById("colour").innerHTML = "Green description"; } else if ('h1:contains("Blue")'){ document.getElementById("colour").innerHTML = "Blue description"; } </script>
…but the content of the p tag won’t change when the H1 tag contains the other text, only the ‘Red’ text seems to work. Please could someone let me know where I am going wrong? Many thanks!
Advertisement
Answer
While there is already an accepted answer, I’m adding this in to show a different approach that I believe to be a bit easier to expand upon for future use.
Finding A Keyword
Similar to the accepted answer, using .includes()
is how we will determine which color/keyword is located in the text, but I also like to use things like .toLowerCase()
when doing string comparisons because case sensitivity can cause things like .includes()
to return false if both words are not capitalized the same way.
Using Objects
if/else
and switch()
statements can be useful, but I often tend to use objects or arrays of objects for situations that involve several different options. Objects also make it a bit easier to add to later on and customize.
const h1 = document.querySelector("h1"), description = document.querySelector("#colour"), colors = [ { color: "red", description: "Red description" }, { color: "orange", description: "Orange description" }, { color: "green", description: "Green description" }, { color: "blue", description: "Blue description" } ] description.innerText = colors.filter(f => h1.innerText.toLowerCase().includes(f.color))[0]?.description
<h1>This is about Red</h1> <p id="colour"></p>
Essentially, this uses .filter()
on the array of objects to find any object whose color
property is found inside of the text of the h1
element.
Expanding/Updating
I don’t know what the planned use-case for this is but I assume that you eventually won’t literally want “Red description” if it finds the word “Red” anywhere in the text. Rather, you will probably have some other wording or sentences, which can easily be set in this object. And adding additional colors is as easy as copying another color/line and changing the text.