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

EDIT:

I learned that using other value than _blank, 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: target="_blank".

  • This does not work on mobile browsers, but it does work on desktop browsers: target="new".

--

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 target="_new" or target="_blank" attribute values to target="nw", 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" title="" attribute.

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 .attr(); methods.

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.

Thanks.

This question is related to jquery

The answer is


Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

Something like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

If you what to add bootstrap attributes in anchor tag dynamically than this will helps you lot

 $(".dropdown a").attr({
      class: "dropdown-toggle",
     'data-toggle': "dropdown",
      role: "button",
     'aria-haspopup': "true",
     'aria-expanded': "true"
});

Use curly brackets and put all the attributes you want to add inside

Example:

$('#objId').attr({
    target: 'nw',
    title: 'Opens in a new window'
});

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})