user1142020
user1142020

Reputation: 13

jquery attr() value isn't being replaced?

First time posting on here, looked through a couple of possible similar titles, still nothing.. :(

Trying to get up to date with jQuery/javascript. Well, my problem is that I would like to change my anchor element's href attribute value depending if the doc width is below 1022px. I've been able to successfully alert the href value, but where I have my commented ALERT (which works) the href string is not updated... Not sure why, any help would be greatly appreciated.

if(document.width < 1022)
{
    var allLinks = $('.filtered_portfolio li a');
    allLinks.each(function(){
        var thisLink = $(this);
        anchorLinkUrl = this
        alert (anchorLinkUrl);

        if( anchorLinkUrl.indexOf('[iframe]=true&lightbox[width]=800&lightbox[height]=540') != -1){
            anchorLinkUrl.replace('[iframe]=true&lightbox[width]=800&lightbox[height]=540','donkey');
            //alert('hi');
        }
    });
}    

Upvotes: 1

Views: 85

Answers (2)

T I
T I

Reputation: 9933

Here is an example of how you can use jQuery's .attr() function to get/set an attribute of a selected element, hope this helps.

$('a').toggle(function(e) {
    e.preventDefault();
    // setting an attribute
    $(this).attr('href', 'www.yahoo.com');
},function(e) {
    e.preventDefault();
    // setting an attribute 
    $(this).attr('href', 'www.google.com');
}).click(function(e) {
    e.preventDefault();
    // getting an attribute
    $('#foo').text($(this).attr('href'));
});

Upvotes: 0

Carl Raymond
Carl Raymond

Reputation: 4479

Your anchorLinkUrl variable is assigned the DOM element, not just the href value. To update the href of the link, try this (untested):

if(document.width < 1022)
        {
            $('.filtered_portfolio li a').each(function(){
                this.href = this.href.replace('[iframe]=true&lightbox[width]=800&lightbox[height]=540','donkey');
                });
        }

Upvotes: 1

Related Questions