An example of using the DOM Attr class

I am working on a project that extends the functionality of the DOM, and I could not provide any reasonable examples of why the class exists Attrand what it can ever be used for.

Given that HTML attributes are always just strings, such as <input type="date" name="your-birthday" />, Elementmethods already exist in the prototype setAttributeand getAttributethat work directly with the attribute value as a string.

An object reference Attrcan be obtained using attr = element.attributes[0], then it can be interacted using methods such as attr.value = "updated value";, for example.

Please, can someone enlighten me with an example of use when I would ever use a class Attr, since it does not have a constructor, and as far as I know, cannot be passed to any methods in the DOM

Link:

+4
source share
1 answer

, , - DOM XML-, URI .

, , MDN Attr.namespaceURI ( ):

Namespaces in XML , . , .

, , XML DOMParser XMLDocument:

<book> id, .

const XML = '<?xml version="1.0" encoding="utf-8"?>\
<books xmlns:lib="http://example.com/xml/library">\
  <book id="book-one" lib:id="1">\
  </book>\
</books>';

var parser = new DOMParser;
var doc = parser.parseFromString( XML, 'application/xml' );

// is our Document an instance of XMLDOcument?
console.log( doc instanceof XMLDocument );

// fetch all Attr instances of the first <book> element
var attributes = doc.querySelector( 'book' ).attributes;
for( var attribute of attributes ) {
  // output namespace info about the Attr instance
  console.log( attribute.localName, attribute.prefix, attribute.namespaceURI, attribute.value );
}
Hide result

- Attr node Element:

div2.setAttributeNode( div1.removeAttributeNode( div1.getAttributeNode( 'class' ) ) );

, , . , Element.getAttributeNode(), Element.getAttributeNodeNS(), Element.setAttributeNode() Element.setAttributeNodeNS() MDN.

DOM w3c.org (. 8.2 DOM Core), DOM whatwg

+2

Source: https://habr.com/ru/post/1679957/


All Articles