General attributes

These methods get and set DOM attributes of elements

attr

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

Set attribute to a single element

jQuery

element.attr('foo', 'bar');

Vanilla JS

element.setAttribute('foo', 'bar');

Set attribute to the set of elements

jQuery

elements.attr('foo', 'bar');

Vanilla ES6+

elements.forEach(x => x.setAttribute('foo', 'bar'));

Vanilla ES5

elements.forEach(function(element) {
    element.setAttribute('foo', 'bar');
});

Get attribute value

jQuery

var value = element.attr('foo');

Vanilla JS

var value = element.getAttribute('foo');

Get plain object containing all element attributes as a name: value pairs

jQuery

var attributes = element.attr();

Vanilla ES6+

var attributes = {};
for (var {name, value} of [...element.attributes])
    attributes[name] = value;

Vanilla ES5

var attributes = {};
[].forEach.call(element.attributes, function(attr) {
    attributes[attr.name] = attr.value;
});

Element attributes is a NamedNodeMap, which is an array-like object, so we can't call array manipulation methods directly.

removeAttr

Remove an attribute from each element in the set of matched elements.

Remove attribute from a single element

jQuery

element.removeAttr('foo');

Vanilla JS

element.removeAttribute('foo');

Remove attribute from the set of elements

jQuery

elements.removeAttr('foo');

Vanilla ES6+

elements.forEach(x => x.removeAttribute('foo'));

Vanilla ES5

elements.forEach(function(element) {
    element.removeAttribute('foo');
});

val

Get the current value of the first element in the set of matched elements or set the value of every matched element.

Get element value

jQuery

var value = element.val();

Vanilla JS

var value = element.value;

Set value to a single element

jQuery

element.val('foo');

Vanilla JS

element.value = 'foo';

Set value to the set of elements

jQuery

elements.val('foo');

Vanilla ES6+

elements.forEach(x => x.value = 'foo');

Vanilla ES5

elements.forEach(function(element) {
    element.value = 'foo';
});
shopify traffic stats