Marie
Marie

Reputation: 2217

Is there a way to modify a specific attribute of every jquery object in one call?

Basically.... I am using this code

var editorLinks;
editorLinks = $(".admin_editor_link.html");
$.each(editorLinks, function(i, link){
    $(link).html($(link).attr("data-loadedtext"));
}); 

And I am wondering if there is some way to do it without the $.each call... like...

editorLinks.html($(this).attr("data-loadedtext"));

I assumed this would work (or some variation of it that I cant remember) but when I tried it all elements html was set to the data-loadedtext of the first element in the array.

Upvotes: 1

Views: 55

Answers (2)

Andy
Andy

Reputation: 63524

Yes, you can, but you'll need to change the name of your class to admin_editor_link because jQuery selector is trying to find elements with both admin_editor_link and html classes. (Unless, of course, you actually looking for elements with both those classes - your question has no HTML code to verify that - in which case you're fine).

<div data-loadedtext="1" class="admin_editor_link"></div>
<div data-loadedtext="2" class="admin_editor_link"></div>

Just use a function to return the result

var editorLinks = $(".admin_editor_link");

editorLinks.html(function () {
  return $(this).attr("data-loadedtext");
});

DEMO

DEMO with both classes

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Use a function supplied to html():

   editorLinks.html(function(){
        return $(this).attr("data-loadedtext");
   });

The return value of the function is used as the value for html() for each element.

Using your example HTML in comment:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/taesc0tt/2/

Upvotes: 2

Related Questions