How can I target an html element that was created INSIDE javascript

EDIT* - I figured it out… I just had some brain lag and forgot you can add “onclick” directly to an element and then just create a function after. I learned about a different way to add event listeners and forgot about the original way I was taught.

this is how I got it to work, if there is another way I’d still like to know! thanks everyone!

So let me try to word this properly.

with .innerHTML i’m able to add a button element after something inside of javascript without actually writing anything inside the HTML document.

`textUnder.innerHTML += `<li> ${inputText.value} </li>`

so, I have this line of code in javascript and I’m going to add a button element inside of it below.

textUnder.innerHTML += `<li> ${inputText.value} <button>x</button> </li>`

so now I have a button that pops up next to my list item and I want to add an eventlistner to that button

now if this button was created in the HTML document, I could easily target it with document.getElementById. However, because it was created in javascript I can’t figure out how to target it to add an event listener.

I’ve added an Id to the button and tried multiple things, but nothing works.

I’m sure this is easy to solve but google isn’t spitting out anything useful. I’m probably not wording the question properly. :sob:

That is one way to do it. But you can’t add the event listener until after you add the button to the DOM.

I think you can just add an id attribute to the element while creating it in javascript.

textUnder.innerHTML += `<li id = ""> ${inputText.value} </li>

can you explain this a bit more? I tried adding an ID to the button but doesn’t document.getElementById only import stuff from the html document?

I don’t understand how to target it if it’s been created inside of Java

Once you add the button to the DOM then you can access it just like any other element on the page. Adding an element with JS is just the same as typing it into an HTML page. They all go into the same DOM.

If you are still having problems then it would probably be best to see your code. If you have it somewhere you can give us a link that would be best. If not then you can paste it in here. To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key.

I’ve figured it out. Thank you so much for the help, it’s truly appreciated!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.