Can you set multiple attributes in javascript?


Set Content - text(), html(), and val()

We will use the same three methods from the previous page to set content:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:

Example

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

Try it Yourself »


A Callback Function for text(), html(), and val()

All of the three jQuery methods above: text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function.

The following example demonstrates text() and html() with a callback function:

Example

$("#btn1").click(function(){
  $("#test1").text(function(i, origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")";
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i, origText){
    return "Old html: " + origText + " New html: Hello <b>world!</b>
    (index: " + i + ")";
  });
});

Try it Yourself »



Set Attributes - attr()

The jQuery attr() method is also used to set/change attribute values.

The following example demonstrates how to change (set) the value of the href attribute in a link:

Example

$("button").click(function(){
  $("#w3s").attr("href", "https://www.w3schools.com/jquery/");
});

Try it Yourself »

The attr() method also allows you to set multiple attributes at the same time.

The following example demonstrates how to set both the href and title attributes at the same time:

Example

$("button").click(function(){
  $("#w3s").attr({
    "href" : "https://www.w3schools.com/jquery/",
    "title" : "W3Schools jQuery Tutorial"
  });
});

Try it Yourself »


A Callback Function for attr()

The jQuery method attr(), also comes with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) attribute value. You then return the string you wish to use as the new attribute value from the function.

The following example demonstrates attr() with a callback function:

Example

$("button").click(function(){
  $("#w3s").attr("href", function(i, origValue){
    return origValue + "/jquery/";
  });
});

Try it Yourself »


jQuery Exercises


jQuery HTML Reference

For a complete overview of all jQuery HTML methods, please go to our jQuery HTML/CSS Reference.



    Table of contents
  • Setting multiple attributes for an element at once with JavaScript
  • Set Style Attribute For Multiple Elements of a Class With JavaScript
  • Can you set multiple attributes with the DOM's setAttribute function?
  • Add multiple data attributes to elements using jQuery
  • Set multiple attributes at once with jQuery

Setting multiple attributes for an element at once with JavaScript

var elem = document.createElement("img");

elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
var elem = document.createElement('img')
Object.assign(elem, {
  className: 'my-image-class',
  src: 'https://dummyimage.com/320x240/ccc/fff.jpg',
  height: 120, // pixels
  width: 160, // pixels
  onclick: function () {
    alert('Clicked!')
  }
})
document.body.appendChild(elem)

// One-liner:
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
.my-image-class {
  height: 100%;
  width: 100%;
  border: solid 5px transparent;
  box-sizing: border-box
}

.my-image-class:hover {
  cursor: pointer;
  border-color: red
}

body { margin:0 }
Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};
var d = document.createElement('div');
d.setAttributes({
    'id':'my_div',
    'class':'my_class',
    'styles':{
        'backgroundColor':'blue',
        'color':'red'
    },
    'html':'lol'
});
function setAttributes(el, attrs) {
    Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}
setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });
function setAttributes(elem /* attribute, value pairs go here */) {
    for (var i = 1; i < arguments.length; i+=2) {
        elem.setAttribute(arguments[i], arguments[i+1]);
    }
}

setAttributes(elem, 
    "src", "http://example.com/something.jpeg",
    "height", "100%",
    "width", "100%");
 function setAttributes(elem, obj) {
     for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
             elem[prop] = obj[prop];
         }
     }
 }

setAttributes(elem, {
    src: "http://example.com/something.jpeg",
    height: "100%",
    width: "100%"
});
function $$(elem) {
    return(new $$.init(elem));
}

$$.init = function(elem) {
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }
    this.elem = elem;
}

$$.init.prototype = {
    set: function(prop, value) {
        this.elem[prop] = value;
        return(this);
    }
};

$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");
const setAttributes = (el, attrs) =>
  Object.entries(attrs)
    .forEach(args =>
      el.setAttribute(...args))
function elemCreate(elType){
  var element = document.createElement(elType);
  if (arguments.length>1){
    var props = [].slice.call(arguments,1), key = props.shift();
    while (key){ 
      element.setAttribute(key,props.shift());
      key = props.shift();
    }
  }
  return element;
}
// usage
var img = elemCreate('img',
            'width','100',
            'height','100',
            'src','http://example.com/something.jpeg');
function setAttribs(elm, ob) {
    //var r = [];
    //var i = 0;
    for (var z in ob) {
        if (ob.hasOwnProperty(z)) {
            try {
                elm[z] = ob[z];
            }
            catch (er) {
                elm.setAttribute(z, ob[z]);
            }
        }
    }
    return elm;
}
Element.prototype.setAttributes = function(obj){
  for(var prop in obj) {
    this.setAttribute(prop, obj[prop])
  }
}
Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }
elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})
let checkbox = document.createElement('input');

for (const [key, value] of Object.entries({
       type: 'checkbox',
       id: 'sys-surname',
       class: 'switcher23',
       value: 1,
       name: 'surname'
 })) {
       checkbox.setAttribute(key, value);
  }
function createNode(node, attributes){
    const el = document.createElement(node);
    for(let key in attributes){
        el.setAttribute(key, attributes[key]);
    }
    return el;
}
const input = createNode('input', {
    name: 'test',
    type: 'text',
    placeholder: 'Test'
});
document.body.appendChild(input);
function SetAtt(elements, attributes) {
    for (var element = 0; element < elements.length; element++) {
        for (var attribute = 0; attribute < attributes.length; attribute += 2) {
            elements[element].setAttribute(attributes[attribute], attributes[attribute + 1]);
        }
    }
}
var Class = document.getElementsByClassName("ClassName"); // class array list
var Data = ['att1', 'val1', 'att2', 'val2', 'att3', 'val3']; //attributes array list
SetAtt(Class, Data);
let elem = document.createElement("img");
Object.entries({"src": "http://example.com/something.jpeg"),
                "height": "100%",
                "width": "100%"}).forEach(kv => elem.setAttribute(kv[0], kv[1]));
let div = document.getElementsByTagName("div")[0];

let attr = ["class", "id", "title"];
let attrVlu = ["ahmed", "mohamed", "ashraf"];

for(let i = 0; i < 3; i++) {
    div.setAttribute(attr[i], attrVlu[i]);
}

Setting multiple attributes for an element at once with JavaScript

function setAttributes(el, attrs) {   for(var key in attrs) {     el.setAttribute(key, attrs[key]);   } } 
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...}); 
var elem = document.createElement('img') Object.assign(elem, {   className: 'my-image-class',   src: 'https://dummyimage.com/320x240/ccc/fff.jpg',   height: 120, // pixels   width: 160, // pixels   onclick: function () {     alert('Clicked!')   } }) document.body.appendChild(elem)  // One-liner: // document.body.appendChild(Object.assign(document.createElement(...), {...}))
.my-image-class {   height: 100%;   width: 100%;   border: solid 5px transparent;   box-sizing: border-box }  .my-image-class:hover {   cursor: pointer;   border-color: red }  body { margin:0 }
Element.prototype.setAttributes = function (attrs) {     for (var idx in attrs) {         if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {             for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}         } else if (idx === 'html') {             this.innerHTML = attrs[idx];         } else {             this.setAttribute(idx, attrs[idx]);         }     } }; 
var d = document.createElement('div'); d.setAttributes({     'id':'my_div',     'class':'my_class',     'styles':{         'backgroundColor':'blue',         'color':'red'     },     'html':'lol' }); 
function setAttributes(el, attrs) {     Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key])); } 
setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' }); 

Set Style Attribute For Multiple Elements of a Class With JavaScript

(function() {
   
var titles = document.querySelectorAll(".my-class");
var i = titles.length;
while (i--) {
    titles[i].setAttribute("style", "cursor:pointer");
}

})();

[code]

YOUR CODE HERE 

[/code]

Can you set multiple attributes with the DOM's setAttribute function?

var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
var attributes = ["class", "type", "checked"];
var values = ["my-class", "checkbox", "checked"];

for (var i = 0; i < attributes.length; i++) {
  input.setAttribute(attributes[i], values[i])
end
var input = document.createElement("input");

function setAttributes(el, options) {
   Object.keys(options).forEach(function(attr) {
     el.setAttribute(attr, options[attr]);
   })
}

setAttributes(input, {"class": "my-class", "type": "checkbox", "checked": "checked"});

console.log(input);
$(input).attr(
{
  "data-test-1": num1, 
  "data-test-2": num2
});
var $input = $("<input>", {class: "my-class", type: "checkbox", checked:"checked"});
function setAttributes(elements, attributes) {
  Object.keys(attributes).forEach(function(name) {
    element.setAttribute(name, attributes[name]);
  })
}
var input = document.createElement("input");
setAttributes(input, {
  class: "my-class",
  type: "checkbox",
  checked: "checked"
})
var opt = {"class":"my-class", "type": "checkbox", "checked":"checked"};

Object.keys(opt).forEach( function(key){ input.setAttribute(key,opt[key]); } );
var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
const input = document.createElement("input");
Object.assign(input, {class: 'my-class', type: 'checkbox', checked: 'checked'});

Is it possible to set multiple data attributes using the jQuery.attr() function?

$(myObj).attr("data-test-1", num1);
$(myObj).attr("data-test-2", num2);
$(myObj).attr({
  data-test-1: num1,
  data-test-2: num2
});
$(myObj).attr({"data-test-1": num1, "data-test-2": num2});
$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});
$('#my_image').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});
/* 
 ** In all the example below, note that 
 ** 'data-' is removed from attribute name
 */

// Setter (single)
$('#my_image').data('test-1', 'num1');
$('#my_image').data('test-2', 'num2');

// Setter (multiple)
$('#my_image').data({'test-1':'num1', 'test-2':'num2'});

// Getter (single)
$('#my_image').data('test-1');    // num1
$('#my_image').data('test-2');    // num2
// Setter
$('#my_image').attr('data-test-3', 'num3');    // note the 'data-' on attr name

// Getter
$('#my_image').data('test-3');    // num3

Add multiple data attributes to elements using jQuery

// global namespace
window.analytics = window.analytics || {};
window.analytics.heatmapping = window.analytics.heatmapping || {};

window.analytics.heatmapping.header = {
    logo: function () {
        var $this = jQuery(this),
            name = $this.closest('ul.navL2').prev().text(),
            type = $this.attr('alt'),
            title = $this.attr('title');

        window.analytics.utilities.setDataAttributes($this, {
            'region': 'header',
            'name': name,
            'type': type,
            'title': title,
            'index': '1'
        });

    } // ... more below,
};

// initializing
jQuery('.top a').each(window.analytics.heatmapping.header.logo);
 /**
 * Set data attributes on an element
 * @param {object} element A jQuery object, typically we'll pass jQuery(this).
 * @param {object} dataAttributes The data attributes we wish to set
 */
window.analytics.utilities.setDataAttributes = function (element, dataAttributes) {
    var util = window.analytics.utilities,
        dataAnalyticsTagAttributes,


    if (util.hasDataAnalyticsTag(element)) {
        dataAnalyticsTagAttributes = util.parseDataAnalyticsTag(element);

        // merge objects
        $.extend(dataAttributes, dataAnalyticsTagAttributes);
    }

    dataAttributes = util.prefixAndTrimProperties(dataAttributes);

    element.attr(dataAttributes);
};

/**
 * Prefixes the incoming objects keys with 'data-' and trims objects values
 * @param  {object} dataAttributes
 * @return {object} dataAttributeWithPrefix
 */
window.analytics.utilities.prefixAndTrimProperties = function (dataAttributes) {
    var util = window.analytics.utilities,
        dataAttributesWithPrefix = {},
        dataKeyWithPrefix,
        dataKey,
        dataValue

    for (dataKey in dataAttributes) {
        if (dataAttributes.hasOwnProperty(dataKey)) {

            // prefix key with data- and trim value
            dataKeyWithPrefix = util.addPrefixToKey(dataKey)
            dataValue = jQuery.trim(dataAttributes[dataKey]);

            // returns new prefixed and clean property in dataAttributesWithPrefix object
            dataAttributesWithPrefix[wedcsKeyWithPrefix] = dataValue;

        }
    }

    return dataAttributesWithPrefix;
};

/**
 * Determines if input element has the data-analytics tag attibute
 * @param  {object} element jQuery(this)
 * @return {Boolean}
 */
window.analytics.utilities.hasDataAnalyticsTag = function(element) {
    return element.is('[data-analyticstag]');
};

/**
 * adds the 'data-' prefix to the input string
 * @param {string} key The objects key it currently iterating on.
 * @return {string} 
 */
window.analytics.utilities.addPrefixToKey = function (key) {
    return 'data-' + key;
}

/**
 * Parses the data-analytics attribute on
 * @param  {object} element A jQuery object, typically we'll pass jQuery(this).
 * @return {object} An object with the properties index, linktype and cmpgrp
 */
window.analytics.utilities.parseDataAnalyticsTag = function (element) {
    var dataAnalyticsAttributeArray = element.attr('data-analyticstag').split('_');

    return {
        'index': dataAnalyticsAttributeArray[4].match(/\d$/),
        'type': dataAnalyticsAttributeArray.splice(0, 4).join(':'),
        'region': dataAnalyticsAttributeArray[3]
    };
};
// @param {string} key The objects key it currently iterating on.
// get any existing attributes from the `data-analyticstag` attribute (if present)
function analyticsTagAttributes(element) {
  // ... see current implementation, and all the stuff above ...
}

// Prefixes keys, and trims values
function prepareAttributes(object) {
  var key, prepared = {};
  for(key in object) {
    if(object.hasOwnProperty(key)) {
      prepared["data-" + key] = $.trim(object[key]);
    }
  }
  return prepared;
}

// extend jQuery
$.fn.extend({
  setAnalyticsAttributes: function (attributes) {
    return this.each(function () {
      var prepared = prepareAttributes(attributes),
          existing = analyticsTagAttributes(this) || {},
          merged = $.extend(existing, prepared);

      $(this).attr(merged);
    });
  }
});
$(elementOrSelector).setAnalyticsAttributes({
  region: 'header',
  name: name,
  type: type,
  title: title,
  index: '1'
});
$(elementOrSelector).analytics()    // returns existing values
$(elementOrSelector).analytics(obj) // sets values

Set multiple attributes at once with jQuery

$('#myimage').attr('src', '/images/myphoto.jpg');
$('#myimage').attr({
    src: '/images/myphoto.jpg',
    width: 200,
    height: 300
});

Next Lesson PHP Tutorial

Can you have multiple data attributes?

Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.

How do I assign multiple values to an attribute?

Perform the following steps:.
Click the Add Another Value link to add a new attribute value row..
From the drop-down list, select an attribute value. The list displays all the values that were defined in Attribute Management screen. ... .
Repeat steps a and b to add more values for the attribute..

How do I add multiple attributes in HTML?

you can simple add an extra attribute by adding a space, and add the attribute.

Can we use more than one attribute with same tag?

In HTML5 PR, section 8.1.2.3 Attributes explicitly says: “There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.”