DasBeasto DasBeasto - 4 months ago 8
Javascript Question

Reference jquery appended element after creation by name?

I'm creating a few jQuery objects that reference elements and appending them to the DOM. I would like to be able to reference them by name so that I don't have to use a bunch of selectors to tie events to them. Here is a dumbed down example
of the code:

<div class="body>

</div>

$(document).ready(function(){
wrapper = $("<div />")
.addClass("wrapper")
.click(function(e){
if (e.target === this)
$(this).hide();
})
$('.body').wrap(wrapper);

close = $("<button />")
.addClass("close")
.text('CLICK TO CLOSE')
.click(function(e){
///HIDE ".wrapper" FROM HERE
$(wrapper).hide();
///HIDE ".wrapper" FROM HERE
})
.prependTo($('.body'));
})


JSFiddle Here

I want to be able to click on the "close" button and hide "wrapper". I could hide it using
$('.wrapper').hide()
but there are going to be multiple wrappers, it needs to target just the one. I could use
$(this).closest('.wrapper').hide()
but now it's getting messy. Is there a way to reference the "wrapper" variable from within "close" to avoid all of the extra code?

Answer

I found out that the issue wasn't with the scope of the click function, it was how the wrap() function worked. When you use jQuery .Wrap() it wraps a copy of the structure around the specified elements and returns the original as a set, which in my case was losing it's reference. So instead of wrapping the .body I simply appended the wrapper where the body was using '.replaceWith' and appended the body to that (essentially .wrap() but in my own way). This worked and allowed me to hide the wrapper using just

wrapper.hide()

Very clean.

Full code:

$(document).ready(function(){
        $body = $('.body');
        wrapper = $("<div />")
                .addClass("wrapper")
                .click(function(e){
                    if (e.target === this)
                        $(this).hide();
                })
                $body.replaceWith(wrapper)
                wrapper.append($body);

        close = $("<button />")
                .addClass("close")
                .text('CLICK TO CLOSE')
                .click(function(e){
                     wrapper.hide();
                })
                .prependTo($('.body'));
})

Working Fiddle: https://jsfiddle.net/1s9o198a/

Comments