I have values that I am pulling from an API, which I am then adding dynamically to the HTML. I have written a function to assign all values that come back as null to be displayed as the text "Not Available" I need to target all the containing tags of the null values (for example the <h2></h2> in <h2>${input.value}</h2> and add a class to display them differently from the rest of the inputs. There is no way to know which value will be null, and it will change every time someone uses the program. Also, the containing tag type will change depending on where the value is being displayed on the page, sometimes an h2, p, or another tag. I have tried,
const notAval = (input) => {
if(!input) {
input = 'Not Available'
}
const allInBody = document.querySelectorAll('body > *')
allInBody.forEach (element => {
if(input === 'Not Available') {
element.classList.add('not-aval')
}
})
return input
}
this is selecting the parent element for example if the footer has the target text in it, the footer is the target, and adds the class to it, but I need to target the tag that actually contains the text.
I am aware that you can use :contains in jQuery but I am trying to use Vanilla JS
Thank you for your help!!
Edit: The content of this question changed after I posted this answer.
You are making a couple of mistakes in the code you pasted.
const notAval = (input) => {
if(!input) {
input.classList.add('not-avail')
}
return input
}
In the above function, you are checking if input is null. Then you are telling your program to add a class to it if it is null. This will always result in an error.
You need to check if input is null, then add the text you want to the html element it should be in.
const el = document.textContent.includes('Not Available')
if(!input) {
el.classList.add('not-avail')
return 'Not Available'
}
In the function above, your are setting el to a boolean value an not an html element. You get an error because you are trying to add a class to a bool.
You need to check if the text content includes the string you want, then add the class to the element itself.