DEV Community

GAURAV YADAV
GAURAV YADAV

Posted on

Cannot add class but elements are already added to the DOM

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)

See the full question here

https://dev.to/dvgy/cannot-add-class-but-elements-are-already-added-to-the-dom-2km8

Top comments (8)

Collapse
 
brianemilius profile image
Brian Emilius

How was the HTML added? Can you post the function that adds the HTML?

Collapse
 
dvgy profile image
GAURAV YADAV

Yes sure.

imgur.com/Cu8fpf6

recipe Render function adds it.

Collapse
 
brianemilius profile image
Brian Emilius

I would love to peek insertAdjacentHTML. I have a suspicion it uses element.innerHTML, which means you cannot manipulate the new DOM elements as they are not available in the current loop.

Thread Thread
 
dvgy profile image
GAURAV YADAV

I didn't understand what you are saying?. What do you mean by "love to peek insertAdjacentHTML" ?

Thread Thread
 
brianemilius profile image
Brian Emilius

I'm sorry, that's my bad. I meant that I just would love to see how that function is made.

Thread Thread
 
dvgy profile image
GAURAV YADAV

Sure wait i will give u link of my code. github.com/DVGY/JavaScript-Project...

My code is here. Pls at Look index.js , searchView.js,base.js and Search.js

Thread Thread
 
brianemilius profile image
Brian Emilius • Edited

Ah yes, okay... I meant the insertAdjecentHTML, which is a native JS method.

I suspected it was using something similar to element.innerHTML under the hood, but the docs on MDN says it works differently.

This was my best bet, though. Sorry I can't help any more than that 😞

Collapse
 
dvgy profile image
GAURAV YADAV

I am okay with that... At least u tried to help me thank for that