This question already has an answer here:
Hey I am trying to add an active class to searchResult HTML using Javascript.
1. I search for recipe in search bar and results are displayed as it is shown in image
Code for the above Image is
Search Controller code
const state = {};
const controlSearch = async () => {
// 1. Get query from view
const query = SearchView.getInput();
if (query) {
//2. New search object and add to state
state.search = new Search(query);
//3. Prepare UI for result
SearchView.clearSearchField();
SearchView.clearResList();
renderLoader(elements.searchRes);
try {
//4. Search for recipies
await state.search.getResult();
//5. Render result on UI
clearLoader();
//This code add HTML
SearchView.renderResults(state.search.result);
} catch (err) {
alert("Error getting Recipe...");
}
}
};
searchView code
export const renderResults = (recipes, page = 1, resPerPage = 10) => {
const start = (page - 1) * resPerPage;
const end = page * resPerPage;
recipes.slice(start, end).forEach(renderRecipe);
renderButtons(page, recipes.length, resPerPage);
};
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);
};
2. Now when I click on recipe list after search it shows an error like this. (I am trying to add a background color to the current recipe click).
Recipe Controller
const controlRecipe = async () => {
const id = window.location.hash.replace("#", "");
if (id) {
// Render UI
RecipeView.clearRecipe();
renderLoader(elements.recipe);
//HighLight Slected
if (state.search) {
SearchView.resultHighlight(id);
}
//State of the recipe object
state.recipe = new Recipe(id);
try {
await state.recipe.getRecipe();
state.recipe.parseIngredients();
state.recipe.calcTime();
state.recipe.calcServing();
clearLoader();
RecipeView.renderRecipe(state.recipe);
} catch (err) {
console.log(err);
alert("Error in getting Recipe");
}
}
};
part of searchView code called in recipe controller which gives error. Why ?
export const resultHighlight = id => {
// const resultArr = Array.from(document.querySelectorAll(".results__link"));
// resultArr.forEach(el => {
// el.classList.remove("results__link--active");
// });
document
.querySelector(`a[href="#${id}"]`)
.classList.add("results__link--active");
};
****NOTE:Following code returns null.Why? Since ** func renderResult() calls, func renderRecipe()** which add HTML code and show search result then why i am resultHighlight is not working ?.
Also after adding function resultHighlight() it showing error, before it was working perfectly **
**document
.querySelector(`a[href="#${id}"]`)**