Sebastian 506563
Sebastian 506563

Reputation: 7248

Why .attr() is working fine and setting a .src is not

I have two versions od code, This one is not working:

 $('#customMenu > li > a').click(function()
            {
                if ($(this).attr('class') != 'active')
                {
                    $('#customMenu li img').each(function() {

                         $(this).src='/_layouts/GAzotyBranding/Images/menuUnselected.png';
                    });
                    var image = this.previousSibling;
                    image.attr('src','/_layouts/GAzotyBranding/Images/menuSelected.png');

                    $('#customMenu li ul').slideUp();
                    $(this).next().slideToggle();
                    $('#customMenu li a').removeClass('active');
                    $(this).addClass('active');
                }
           });

and this one is working fine:

$('#customMenu > li > a').click(function()
            {
                if ($(this).attr('class') != 'active')
                {
                    $('#customMenu li img').each(function() {
                        $(this).attr('src','/_layouts/GAzotyBranding/Images/menuUnselected.png');

                    });
                    var image = this.previousSibling;
                    image.src='/_layouts/GAzotyBranding/Images/menuSelected.png';
                    $('#customMenu li ul').slideUp();
                    $(this).next().slideToggle();
                    $('#customMenu li a').removeClass('active');
                    $(this).addClass('active');
                }
           });

the only difference is in

$('#customMenu li img').each(function() {
                        $(this).attr('src','/_layouts/GAzotyBranding/Images/menuUnselected.png');

My Question is simple, why first one is not working?

Upvotes: 0

Views: 40

Answers (2)

Quentin
Quentin

Reputation: 944568

Because setting a src property on a jQuery object simply doesn't do anything. There's no defined behaviour for it and nothing pays attention to it. jQuery objects are not DOM objects.

Using this.src instead of $(this).src would work.

Upvotes: 0

Evan Trimboli
Evan Trimboli

Reputation: 30092

Because in both cases you're wrapping the raw DOM node with the jQuery wrapper, so you're just setting some property on a non-DOM object.

To make the first work, you'd need to have this.src = '...';, since this will point to the raw DOM element.

Upvotes: 1

Related Questions