There and That
There and That

Reputation: 165

Access and set the value of non standard attributes with hyphens

I'm trying read and write values of non standard attributes with hyphens in the name. These attributes are being created by a library called gridstack, so I cant just use data- atttributes.

As an example, I have an element with the following content;

<div class="grid-stack-item ui-draggable ui-resizable" gs-x="0" gs-y="0" gs-w="1" gs-h="4" gs-id="4">...</div>;

I'm attempting to read/set the gs-h attribute.

So these do not work;

// Element is just the dom object containing the above div.
var element = $('#dPanel' + id)[0].parentNode.parentNode; 

var h = element.getAttribute('gs-h'); // Doesnt work
var h = $(element).attr('gs-h');      // Doesnt work
$(element).attr('gs-h', '1');         // Doesnt work

I could just yank the value out by parsing the innerHtml, but that does not let me set the value.

Upvotes: 0

Views: 148

Answers (1)

laoyb
laoyb

Reputation: 109

for vanilla js, might try the DOM property attributes :

The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a NamedNodeMap, not an Array ...

e.g. to retrieve the value of a non-standard attribute url of a <a> element, just simply do like

const url = element.attributes['url'].nodeValue

Upvotes: 0

Related Questions