Hey I am trying to add an active class to searchResult HTML using Javascript.
I try to search for recipe in search bar and results are displayed as it is shown in image.
Search Result
https://i.stack.imgur.com/vWj4m.jpg
When I click on a recipe from the search list I want to add a background color to the currently selected recipe(click on the recipe) using function resultHighlight()
function resultHighlight() is being called in the controller and produces an error. Since the HTML is already added(after a search query is fired) by function renderRecipe() then why it is unable to find href id and producing error ?
//Function to add background color
export const resultHighlight = id => {
document
.querySelector(a[href="#${id}"]
)
.classList.add("results__link--active");
};
Error Image
https://i.stack.imgur.com/m372A.jpg
NOTE: I tried console logging follwoing part and it returns null.
document.querySelector(a[href="#${id}"]
)
//OUTPUT: null
JavaScript has already added HTML by a function (Search result)
//Function to add search result on UI
const renderRecipe = recipe => {
const markup =
;
<li>
<a class="results__link results__link--active" href="#${recipe.recipe_id}">
<figure class="results__fig">
<img src="${recipe.image_url}" alt="${recipe.title}">
</figure>
<div class="results__data">
<h4 class="results__name">${reduceRecipeTitle(recipe.title)}</h4>
<p class="results__author">${recipe.publisher}</p>
</div>
</a>
</li>
elements.searchResList.insertAdjacentHTML("beforeend", markup);
};
Top comments (5)
Could it be something to do with the syntax of
In the docs is says that if
does not find the selector it returns null.
Hey Dylan, as far as i Know the syntax is correct . I was following this video. youtube.com/watch?v=fCfdpM2d0vg&li...
TimeStamp : 10:00 to end of videos(7 min watch )
Im the video I see he wraps
In backticks like this
That might be it.
Ya that is known as temple string. Even i did the same
. Sorry i don't know why it's not showing here,but in my real code i have added template string only. Still it doesn't work
having the same issue here