Preet
Preet

Reputation: 7

How to use value of own attribute in javascript

<button own-attribute="value1 value2">Button</button>

i want to use the values value1 & value2 of own-attribute in javascript to make changes in the style of <button>.

Upvotes: 1

Views: 110

Answers (1)

Sirko
Sirko

Reputation: 74076

In a CSS only solution you can use attribute selectors to target such elements:

button[own-attribute~="value1"] {
  color: blue;
}

Using attributeName~=value you can target a single value, if your attribute contains a space separated list of values.


Note, however, that custom attributes should use the data--prefix to prevent collisions with native attribute names.


If you want to just retriebe the element to further process it in JS, use the same selector:

// to contain just one of the values
var el = document.querySelector( 'button[own-attribute~="value1"]' );

// to contain both values, no matter the order
var otherEl = document.querySelector( 'button[own-attribute~="value1"][own-attribute~="value2"]' );

Upvotes: 3

Related Questions