'Parameter won't work outside of $() - jQuery

I have a simple AJAX script and I am curious why the parameter won't work outside $() block:

var loadWork = function(el) { //element which href will be used
    var url = $(el).attr('href'); //it doesn't work if 'el' is not in $()
    $.get(url, function(data) {
        $('#work-gallery').html(data);
    });

}

$(document).ready(function() {
    loadWork('#work ul li a[href="includes/wdes.html"]')
    $('#work ul li a').click(function(evt) {
        evt.preventDefault();
        var element = $(this);
        loadWork(element);
    });
});

That el (short for element) parameter of the loadWork function needs to be inside $() in *var url = ...* expression. Why is that, when I pass it as either a variable or literal element in function call?



Solution 1:[1]

you are passing a string, so if you would not wrap it by $() it will just be a string, so would be similiar to

'#work ul li a[href="includes/wdes.html"]'.attr('xyz')

but thats nonsense as the .attr method is a property of jqueryObjects, so using

$('#work ul li a[href="includes/wdes.html"]')

will select the matching domnodes and wrap them as jquery Object so you can run jquery methods like .attr()

Solution 2:[2]

What you are trying to do:

"On clicking a a link inside #work, load whatever the href of that link returns into #work-gallery."

For simple content loading jobs, there is the .load() jQuery function, which takes a URL and puts the returned HTML inside an element – just what you are doing in your loadWork() function. So let's scratch that function, it's superfluous.

Second, you want to load something initially. It's easiest to simply trigger the click event on one of the links, since we already have the proper click handler.

$(document).ready(function() {
    $('#work a').click(function (e) {
        e.preventDefault();
        $('#work-gallery').load(this.href);
    }).first().click();
});

Note how this inside the event handler points to the DOM object, so you can use this.href directly instead of taking the detour of calling .attr('href').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 john Smith
Solution 2 Tomalak