/    Sign up×
Community /Pin to ProfileBookmark

Using $.get method to assign data attribute.

Hi, I need help.
I have a function that loops through all the links and assigns a default data-content attribute.

`getContent: function () {
$(‘ul#links a’).each(function () {
var t = $(this),
content = ‘this is a default content’;
t.attr(‘data – content’, content.tolowercase());
})
}`

I want to replace the default data-content with the content from the link but I can’t get it to work.
I’m thinking something similar to this.

`getContent: function () {
$(‘ul#links a’).each(function () {
var t = $(this),
content = $.get(t.attr(‘href’)
t.attr(‘data – content’, content.tolowercase());
})
}`

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumNov 20.2019 — I recommend reading the docu of $.get:

https://api.jquery.com/jquery.get/

The function $.get does not return the response of the server but:
all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object.[/quote]
which is not what you require.

In order to access the response of the server you need to use the success callback function. It will have the response as a parameter. This should work (untested):
getContent: function () {
$('ul#links a').each(function () {
var t = $(this);
$.get(t.attr('href'),
function (response) {
t.attr('data-content', response.tolowercase());
}
);
})
}

You might also use the function data:

https://api.jquery.com/data/
Copy linkTweet thisAlerts:
@mbc016authorNov 20.2019 — @Sempervivum#1611000 Hi! It worked. Thank you very much! :)
Copy linkTweet thisAlerts:
@siddhi_patelNov 21.2019 — HI...

u can use like this ..

$.get function does not return the response of the server but all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object.

``<i>
</i>
getContent: function () {
$('ul#links a').each(function () {
var t = $(this);
$.get(t.attr('href'),
function (response) {
t.attr('data-content', response.tolowercase());
}
);
})
}<i>
</i>
``
×

Success!

Help @mbc016 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...