Click here to Skip to main content
15,921,179 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So, I have elements in my HTML is I am using JavaScript that when I click on them new elements show up. The new elements are being added dynamically by filtering and using the map function. The new elements content is coming from an array of objects (that is what I am using the map function and filtering for).

Everything works fine but I would like to be able to access the class attached to the content that is being added dynamically.

Originally I have been adding the dynamic content via inner HTML but then can't access the class that is being added dynamically with the other HTML content.

From research I found out that creating a template with JavaScript and adding HTML stored in a variable works. Get it to work with the HTML code I am adding dynamically with mapping and filtering.

What my end goal is, is to be able to have a click event on the dynamically added content so that I can click on them and have new dynamically added content show up.

I know to click on dynamically added content you could bind a click event. But when I do this I still can’t get new content to show up when I click on the dynamically added content.

I can just get the click event to work on the elements I have in my HTML and bring up one set of dynamically added content when click on them.

What I have tried:

Here is a code pen link to my original code that works totally fine but I cant access the new class attached to the content being added dynamically. How could I keep everything as it is and possibly add a template with JavaScript or some other way to access the new class so I can generate new content when an element is clicked on?

Or if there is another way of achieving what I’m after that would be great!

Here is the link https://codepen.io/emilyray2720/pen/KKWrNPq[^]
Posted
Updated 14-Jun-21 23:32pm

1 solution

There are two parts of the code which need addressing really. The first is that the portfolioHeadingContainer appears to be null. This means that it wasn't found on the document, so the JS produces an error once the displayProjectItems() method is called.

The second is that you can bind events to new elements once the DOM has been updated. In your displayProjectItems() method you're setting the innerHTML property of the container, which then updates the DOM. Once that's been done you can bind to click events of the new children by simply running query selectors afterward.

JavaScript
portfolioGrid.innerHTML = displayProjectItem;

const children = document.querySelectorAll('.portfolio__item');
console.log(`I have managed to find ${children.length} children!`);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900