J. Doe
J. Doe

Reputation: 107

How to set multiple attributes to the same value?

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

Answers (4)

J. Doe
J. Doe

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

Hassan Imam
Hassan Imam

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

Obsidian Age
Obsidian Age

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

guradio
guradio

Reputation: 15555

  1. Add in array

$('#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

Related Questions