three7studio three7studio - 7 months ago 11
Javascript Question

Append div Above parent of specific div with changing order in dom

So this may be possible but I'm not able to figure this one out... I need to inject a div into the parent of a nested element and have it appended before that elements parent... The trouble comes when I can't target the location by looking for the specific instance in the parent. Hopefully the code will clarify

I need to Use the id from the nested div

<div>
<div></div>
<div></div>
<div>
<div>
<div id="startFromHere"></div>
</div>
</div>
<div></div>
<div></div>
</div>


And insert a div above the main parents location in the list

<div>
<div></div>
<div></div>
<div id="theAppendedDiv"></div>
<div>
<div>
<div id="startFromHere"></div>
</div>
</div>
<div></div>
<div></div>
</div>


I can not target the 3rd element in the list because the div with the ID I need targeted will not stay in the 3rd position, it will change. So if its the 5th item or the 2nd item, I have to append a div before the parent of that specific nested div.

I also have no control over the html and have to inject this through js/jquery. It could be up to 10 levels deep, nested in spans/tables/divs ect... None of the parent elements are labeled, The only thing I can use to target anything is a nested elements ID.

Answer

You can use parent() method like following.

$('#startFromHere').parent().parent().before('<div id="theAppendedDiv">The Appended Div<div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>1</div>
    <div>2</div>
    <div>
        <div>
            <div id="startFromHere">Start From Here</div>
        </div>
    </div>
    <div>4</div>
    <div>5</div>
</div>