Note that there are some explanatory texts on larger screens.

plurals
  1. POGet parent of appended element
    primarykey
    data
    text
    <p>I have inserted elements into the DOM with <code>appendTo()</code>. I am tryng to traverse the DOM from inside the appended elements to get a reference back to the element that the appened elements were appended to. But this does not seem to be working for me. I've done some troubleshooting by outputing the result of <code>parent()</code> to the console. Each time I step back one level I get a result from <code>parent()</code> until I reach the parent of the appended element. At that point <code>parent()</code> returns an empty set. </p> <p>Here's an example of the code to illustrate this problem:</p> <pre><code> &lt;div class="menu"&gt; &lt;span class="like current"&gt;&lt;/span&gt; &lt;span class="done"&gt;&lt;/span&gt; &lt;span class="add"&gt;&lt;/span&gt; &lt;span class="report"&gt;&lt;/span&gt; &lt;div class="panel"&gt; &lt;div class="panel-content"&gt; &lt;p&gt;This function is not yet implemented&lt;/p&gt; &lt;p&gt; &lt;a class="cancel" onclick="cancel_panel(this)"&gt;Cancel&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><code>div.panel</code> has been appended to <code>div.menu</code> with <code>appendTo()</code> and <code>div.panel-content</code> has been appended to <code>div.panel</code> with <code>appendTo()</code></p> <p>What I'm trying to achieve is to remove class <code>current</code> from <code>span.like</code> on clicking the Cancel link.</p> <p>I've tried:</p> <pre><code> $(elem).closest("div.menu").children("span.current").removeClass("current"); </code></pre> <p>(where elem is a reference to the <code>a</code> element of the Cancel link)</p> <p>But it doesn't work. <code>$(elem).closest("div.menu")</code> returns an empty set instead of <code>div.menu</code></p> <p>In further troubleshooting, <code>$(elem).parent()</code> gives me the expected reference to the <code>p</code> tag, <code>$(elem).parent().parent().parent()</code> gives me the expected reference to <code>div.panel</code>. But <code>$(elem).parent().parent().parent().parent()</code> returns an empty set.</p> <p>What's going on here? Do appended elements not respond in the same way as real elements when traversing the DOM? Does jquery loose the plot with nested appends? How can I get a reference to back to the <code>div.menu</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload