Reputation: 107
Say I have an anchor:
<a id="link" href="" title="">Link</a>
And I want to set both the href and title to an url at the same time. So something like this:
$('#link').attr('href title', 'http://stackoverflow.com');
Is there a way to do something like this?
Upvotes: 0
Views: 1841
Reputation: 107
I think I have found the best answer, created a variable inside the attr() function:
$('#link').attr({'href': (a = 'http://stackoverflow.com'), 'title': a});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
Upvotes: 0
Reputation: 22524
You need to chain them together.
$('#link')
.attr('href','http://stackoverflow.com')
.attr('title','http://stackoverflow.com');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
You can use jquery#each
and iterate through your attribute array and assign your url
to them.
let url = 'http://stackoverflow.com';
$.each(['href','title'],
function(index, name) {
$('#link').attr(name, url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
Upvotes: 1
Reputation: 42304
You can chain jQuery methods together, such as in the following:
var target = "http://stackoverflow.com";
$('#link')
.attr('href', target)
.attr('title', target);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
Or pass an object to the method, where the two different attributes are the keys:
var target = "http://stackoverflow.com";
$('#link').attr({
title: target,
href: target,
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
Hope this helps! :)
Upvotes: 1
Reputation: 15555
$('#link').attr({
title:"http://stackoverflow.com",
href:"http://stackoverflow.com",
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="" title="">Link</a>
Upvotes: 1