How can I prepend to a class specifically descended from $(this) e.g. I only want to prepend to the div that’s actually clicked in this example…
<div>
<div class='target'></div>
</div>
<div>
<div class='target'></div>
</div>
$('div').click(function(){
$('<div>hello</div>').prependTo('.target');
});
Only hook the relevant divs, then use
thiswithin the handler (but see also below, I can read your question two different ways):Within an event handler hooked up via jQuery,
thisrefers to the specific DOM element you hooked the handler to that received the event. See thebindorondocumentation for details.Live example (You also had the
}and)at the end reversed, causing a syntax error.)If your goal is to have a click anywhere on the outer div prepend in front of the target div, it’s more like this:
Live example There we’re using
thisagain, but this time we’re using it to find out if thedivthe event has propagated to contains adivwith the class “target”. If so, we prepend your “hello” div and stop the event viareturn false;(you could useevent.stopPropagation();instead).