I’m quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don’t have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you’re generating
id. For example:if you always generate
idlike:myid1,myid2,myid3…then you can try:
OR
Here,
^=is start with selector, sodiv[id^=myid]will selectdivwhoseidstart withmyid.You can also use Contain word selector which is
~=and use like$('div[id~=myid]'). This will selectdivwithidcontains wordmyid.Instead of
idif you want to use other attribute eg.namethen change selector like:$('div[name^=myid]')or$('div[name~=myid]').