Quantcast
Channel: Active questions tagged visual-studio-code - Stack Overflow
Viewing all articles
Browse latest Browse all 98777

Cannot add class but elements are already added to the DOM [duplicate]

$
0
0

This question already has an answer here:

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

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 functionresultHighlight()

functionresultHighlight() 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

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);
    };

Viewing all articles
Browse latest Browse all 98777

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>