Search code examples
javascriptjqueryhtmlwrapperunwrap

jQuery problem in the wrap/unwrap procedure


Consider the following code:

$(".lcontainer a").click(function () {
    var current = $(this);
    var name = current.attr('href');
    document.getElementsByName('source')[0].value = name;
    var fPicture = "css/imgs/Flash.png";
    //If image is wrapped in link unwrap it
    var newLink = $('<a/>').attr('href', name);
    newLink.find('#prev').unwrap();
    if (extension == "jpg" || extension == "png" || extension == "gif" || extension == "bmp") {
        $(".mainCategory").html("Picture");
        document.getElementById('prev').src = name;
    }
    else if (extension == "swf") {
        $(".mainCategory").html("Game");
        document.getElementById('prev').src = fPicture;
        previewImage.wrap(newLink);
    }
    return false;
});
});

The logic is simple: if we have swf file put flash symbol and wrap the symbol with link pointing to this file. The problem: click another link and the symbol is not unwrapped.


Solution

  • You're creating a new link element with:

    var newLink = $('<a/>').attr('href', name);
    

    ...so this:

    newLink.find('#prev').unwrap();
    

    ... won't find anything because newLink doesn't have anything inside it yet.

    Are you certain you didn't want to do something like this?

    $('#prev').unwrap();
    var newLink = $('<a/>').attr('href', name);