Only Bolivian Here
Only Bolivian Here

Reputation: 36733

jQuery object doesn't prepend at all

I want to insert an object ($roleOption) when someone clicks on the add image. The else condition works fine and exactly how I want it to.

But the first condition ("insert directly before the image if there are no options") isn't working at all. No errors are fired, it just doesn't prepend the object.

Am I using the prepend method incorrectly?

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var $roleOption = "<div class='roleoption'><img src='@Url.Content("~/Public/images/delete.png")' alt='delete' />@Html.Raw(@DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRoleJavascript(Model.ExistingRoles, 1))</div>";

        $('img.add-role').click(function() {
            if ($(this).siblings('.roleoption').length == 0) {

                //Displaying zero as expected. So it's entering this conditional.
                console.log($(this).siblings('.roleoption').length); 
                $(this).prepend($roleOption); //However the element isn't being prepended. :/
            }
            else {
                $($roleOption).insertAfter($(this).parent().find('.roleoption:last')); //This works as expected.
            }
        });
    });
</script>

Upvotes: 2

Views: 865

Answers (1)

Phil
Phil

Reputation: 164760

You can't insert content into an <img> tag (which is what prepend() is attempting to do).

Use before() instead.

Upvotes: 4

Related Questions