EHorodyski
EHorodyski

Reputation: 794

Using .load with an element's attribute

Using jQuery 2.0.3, I'm having issues trying to do something like so:

$("[data-load]").load($(this).attr("data-load"));"

And the associated HTML looks like: <div data-load="markup/fonts.html"></div>

I can retrieve the correct value from the attribute but I can't get it to load anything. What's more, if I try $("[data-load]").load($(this).attr("data-load").toString()); I get an Error: Unable to get value of the property 'toString': object is null or undefined

Any clues?

Edit: Sorry, syntax was correct. Just wrong when typing it here.

Resolution: Jeez, I'm a bonehead. What I was looking for what this:

$("[data-load]").each(function (index) {
    $(this).load($(this).attr("data-load"));
});

Upvotes: 0

Views: 266

Answers (3)

Anthony Grist
Anthony Grist

Reputation: 38345

If you want all elements that have a data-load attribute, regardless of its value, you have the correct selector:

$("[data-load]")

However, the problem is when you're calling the .load() function; you need a way to refer to a specific element. I'd suggest using .each():

$('[data-load]').each(function() {
    $(this).load($(this).attr('data-load'));
});

That iterates through each of the elements that matched the selector, individually calling .load() on them and passing the data-load attributes value for that specific element to it.

Upvotes: 0

EHorodyski
EHorodyski

Reputation: 794

Resolution: Jeez, I'm a bonehead. What I was looking for what this:

$("[data-load]").each(function (index) {
    $(this).load($(this).attr("data-load"));
});

Upvotes: 1

vladkras
vladkras

Reputation: 17227

why $("[data-load]) - you forgot one more "?

Upvotes: 1

Related Questions