I cant figure out how to set a name to an element that is created in javascript

Sorry im on a phone and do not have access to code so i will do my best to explain. I have no internet at the moment.

So basically I have a div container in my html file that is empty.

I then pulled that container into JS with getElementByClassName and used
divContainer.innerHTML to create some elements within it. Now since those elements dont actually exist in my html. I do not understand how to asign a name to them so i can actually target them.

I cant actully use something like

Let exampleEl = document.getelebyid(‘example’)

And have that variable name of exampleEl to target because it’s already in my JS, i cant find out how to turn any of those elements into variables so I can actually target them.

Sorry about the hard to read grammar, i hage typing this much on a phone.

I hope this made sense!

just use a different variable name?
(i’m not sure if you’re asking a javascript question or an html question).

if javascript, then use any name u like on the left hand side of the equals.
If html, then give any id you like to the element.

edit: or are you asking ‘how do I target an element that didn’t exist when I created it in my javascript code’?
You can target it many ways. If you are creating it you can give it an id.
Or you can use something like querySelector function and target based on the position of the element w.r.t its parents.

Im saying the element didnt exist in my html, only the container did.

Then i did

divContainer.innerHTML = ’
<h.1>hello world<h.1>’

That h1 element does not exist in the html and was created in javascript.

But i want to turn it into a javascript variable.

I know how to pull elements from html and asign them to a javascript variable but i cant target that h1 by id or classname. Ive tried and it returned null.

You can target the element after you have created it and added it to the DOM. The DOM methods are not looking at the HTML, they are looking at the live DOM structure.

You can also give the element an id, a class, or whatever to target it with.

const root = document.getElementById('root');

root.innerHTML = `<p id="text">text</p>`
const text = document.getElementById('text');
text.textContent = 'New text';

I think i may have figured it out.

I think the issue stemmed from the elements not being created until a button click. I might have to write code within the button click

The mentioning of targeting the children is what got me through. Thank you both! I know my wording was hard to understand.

1 Like

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