<div id="banana" class="fruit">
<div>
<p>
some text
</p>
</div>
</div>
<div id="apple" class="fruit">
<div>
<p id="test">
some text
</p>
</div>
</div>
<div id="cherry" class="fruit">
<div>
<p>
some text
</p>
</div>
</div>
JavaScript
// you're running a query starting from the window (this) and looking up for more elements - but window has no parents.
// var id = jQuery( this ).closest( ".fruit" ).attr( "id" );
// so here id is undefined
// jQuery( 'p#test' ).append( id );
// try this instead... ($ is jQuery)
// wait for the DOM to be ready first
$(function () {
// get your test element
var testElement = $('p#test');
// look for the fruit parent
var parentFruit = testElement.closest('.fruit');
// if you find one
if (parentFruit.size()) {
// write it's id to your element
testElement.append(parentFruit.attr('id'));
}
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.