How do I add event listeners on click to the edit button and make them edit different sections if the classes and HTML code is the same for all edit buttons
<div className="top-row">
<div className="left-header">ABOUT ME</div>
<div className="right-header">Edit</div>
</div>
<div className="bottom-row">
...
<div className="top-row">
<div className="left-header">PLEASE UPDATE YOUR LINKS</div>
<div className="right-header">Edit</div>
</div>
<div className="bottom-row">
getElementByClassName()
does not seem to work
4
Answers
I resolved this in codesandbox.
https://codesandbox.io/s/boring-edison-hii8rb?file=/index.html
you can use querySelectorAll to catch all elements if this class, and use forEach to iterate them.
I found an error, you use class as className, this is used in React, in HTML we use only class, because this you can’t get with getElementsByClassName function.
Your question is a bit confusing, because you’re asking for help re-creating the functionality of a site based on its HTML, but you tagged this question with
React
, so if you’re just using HTML to code this site, then @JoSSte is right, you can just use unique ids to select the elements in question. You could also usegetElementsByClassName
and write individualaddEventListener
callbacks for each item in the resultant array. That would look something like this:If you’re looking to execute different actions for each Edit button using React, but the site that you’re trying to clone isn’t utilizing unique ids for each one, then it’s likely they’re probably using
props
to pass the information for each action into a component that’s being called multiple times.For example, you could do something like this in your components:
Code is a bit choppy, but hopefully that helps!
You’d need to use a selector that is position based to qualify it.
Also, your HTML is incorrect, you should be using
class
notclassName
.className
is used in JavaScript to access a list of all the classes applied to an element. In HTML, you just use theclass
attribute.See comments below:
A number of ways to do this based on element classes, position of the type, based on data attributes etc.
Here are a few examples.