How can I refer to a DOM element on a DOM element?

I know that there are many similar questions, and I looked through them. This was not enough. So.

I have a situation where I need to duplicate an element and find out the original element from which I cloned, so I do it like this, which is ugly:

<div id="main"> <p>Hello</p> </div> 

then

 $(somewhere).append( $('#main') .clone() .attr('src', 'main') )); 

Now this is very ugly as I was attaching an identifier from the original element that I cloned. In my situation, I don't know if the element has an identifier, so I could create a random one and assign it like this:

 var id = $(element).attr('id'); if (!id) { var id = 'id_'+ Math.round(Math.random()*99999999); $(element).attr('id', id); } $(somewhere).append( $(element) .clone() .attr('src', id) )); 

My decisions seem very dirty to me, and I have a chance to run into, of course ... so I would like to know any clean way to refer to a DOM element from another element.

UPDATE

So in conclusion, I used jQuery .uniqueId(). and just .attr() item id via .attr() as $(el).attr('src', $(parent).attr('id') );

+4
source share
3 answers

Use class names and change the new (cloned) element with a custom property:

HTML

 <div class="main"> <p>Hello</p> </div> 

JQuery

 currentObj = $(".main"); //Object of the cloned element clonedElement = currentObj.clone().addClass("cloned"); //Assign a reference with custom property clonedElement[0].clonedFrom = currentObj; $(somewhere).append(clonedElement); 
+2
source

You can query the DOM for an element with an identifier that you created. If nothing is found, then it is unique if such an element is repeated with a new random identifier.

+2
source

Try it like this.

 <div class="main"> <p>Hello</p> </div> 

// jQuery code

 currentObj = $(".main"); //Object of the cloned element clonedElement = currentObj.clone(); $(somewhere).append(clonedElement); 

If you want to add a unique identifier to the elements, you can do it like this from jquery1.9.1 onwards

 currentObj.uniqueId(); clonedElement.uniqueId(); 
+1
source

Source: https://habr.com/ru/post/1485597/


All Articles