Ricardo Zea Ricardo Zea - 1 month ago 5x
jQuery Question

jQuery: Adding two attributes via the .attr(); method


I learned that using other value than

, DOES NOT work on mobile browsers to open new windows/tabs.

For example, if you need to open a new window/tab:

  • This works on all browsers, even mobile browsers:

  • This does not work on mobile browsers, but it does work on desktop browsers:


Although I have this one working, I'm not sure if there's a better way to do it, or if the way I got it is the right/only way.

Basically what I'm doing is replacing all the
attribute values to
, this way only one new window is open and in it all other new windows will open in order to not overwhelm the user with multiple windows.

I'm also adding a "Opens in a new window"

So the solution I created is this one:

$("a[target='_blank'], a[target='_new']").attr('target','nw').attr('title','Opens in a new window');

Notice the two

Is this the correct way to add two attributes to an element?

I tried
.attr('target','nw','title','Opens in a new window')
but it didn't work.

The reason I ask is because of the DYR (Don't Repeat Yourself) principle, so if I can improve the code I have, great, if not, then it is what it is.



Should work:

    title:"Opens in a new window"


" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use


To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it