Can I add arbitrary properties to DOM objects? - javascript

Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT> or <SELECT> elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?

ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.
const wm = new WeakMap();
el = document.getElementById("myelement");
wm.set(el, "my value");
console.log(wm.get(el)); // "my value"
Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.

Yes, you can add your own properties to DOM objects, but remember to take care to avoid naming collisions and circular references.
document.getElementById("myElement").myProperty = "my value";
HTML5 introduced a valid way of attaching data to elements via the markup - using the data- attribute prefix. You can use this method in HTML 4 documents with no issues too, but they will not validate:
<div id="myElement" data-myproperty="my value"></div>
Which you can access via JavaScript using getAttribute():
document.getElementById("myElement").getAttribute("data-myproperty");

Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.
If you are looping code with for..in your code may break because you will now be enumerating through these newly attached properties.
I suggest using something like jQuery's .data which keeps metadata attached to objects. If you don't want to use a library, re-implement jQuery.data

Do you want to add properties to the object, or attributes to the element?
You can add attributes using setAttribute
var el = document.getElementById('myelement');
el.setAttribute('custom', 'value');
or you can just add properties to the javascript object:
var el = document.getElementById('myelement');
el.myProperty = 'myValue';

In case someone is wondering in 2015, yes, you can - and jQuery is doing just that in data. Just pick future-proof names like vendor prefixes or time-based random suffixes (jQuery).

If you must, don't use standard HTML attributes. Here's a tutorial on using custom attributes:
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
It's HTML5, but it's backward-compatible.

I was exploring answers, none have mentioned that in modern JavaScript we can set attributes on domElements using dataset property, it could use on HTMLOrForeignElement (that's a mixin of several features common to the HTMLElement, SVGElement and MathMLElement interfaces).
According to MDN
The dataset property on the HTMLOrForeignElement interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM. It is a map of DOMStrings, one entry for each custom data attribute.
let element = document.getElementById("test");
let footer = document.querySelector("#output");
/* get element values using camelCase names through .dataset */
let sample = element.dataset.sample;
let sampleNumber = element.dataset.sampleNumber;
let dataFromElement = sample + " :: " + sampleNumber;
footer.innerHTML = element.innerHTML + dataFromElement;
<input type="hidden" id="test" data-sample="Sample" data-sample-number=34 />
<div id="output"> </div>
Although there are concerns about Internet Explorer support and performance on this you can check here.

Related

How to get all possible valid attributes on a DOM element [duplicate]

This question already has answers here:
How to list all element attributes in JS?
(3 answers)
Closed 5 years ago.
Please note that .attributes only gets the current attributes, which is not what this question is about.
I want a way to get all the attributes of a DOM element. Not just the ones that are on it now, but the ones that are possible in the future too.
The specific use case is to find the potential attributes in an SVGElement that aren't in an HTMLElement - there's a list on MDN (SVG Attribute reference), but, for obvious reasons, hardcoding is not a good idea.
My initial thought was to iterate through the prototype chain of an instance of each and compare the two lists (with basic filtering for event handlers), but this doesn't actually give the potential svg attributes.
EDIT
IMPORTANT NOTE - pasting your answer code into the console on this page and using document.body as a target should show a list of over 50 attributes, including things like contentEditable, contextMenu, dir, style, etc.
This also needs to work cross-browser.
Could something like this be what you're looking for?
It looks like a DOM element object stores empty keys for all possible attributes. Could you loop over these keys and store them in an array, then from there use something similar to filter out inherited attributes?
HTML
<svg id="blah"></svg>
Javascript
const blah = document.getElementById('blah')
let possibleKeys = []
for (let key in blah) {
possibleKeys.push(key)
}
Here's a JSBin example ... it looks like it produces a list of all possible attributes but it would need some filtering.
See also this thread.
How to list all element attributes in JS?
Any one of these should work because they return a live HTMLCollection.
var svgElement = window.document.getElementsByClassName("someSvgClass")[0];
//assume someSvgClass is on svg element.
//var svgElement = window.document.getElementsByTagName("svg")[0];
//var svgElement = window.document.getElementsByName("mySvg")[0];
//assume svg has this name.
var svgAttributes = svgElement.attributes;
for(let i=0; i<svgAttributes.length; i++) {
console.log(svgAttributes[i]);
}
See the below documentation from MDN on getElementsByTagName()
The Element.getElementsByTagName() method returns a live
HTMLCollection of elements with the given tag name. The subtree
underneath the specified element is searched, excluding the element
itself. The returned list is live, meaning that it updates itself with
the DOM tree automatically. Consequently, there is no need to call
several times Element.getElementsByTagName() with the same element and
arguments.
The documentation for getElementsByName , and getElementsByClassName say the same thing; a live node list is returned. If you'd like to try it, I created a fiddle here.
You'll see that svgAttributes list is automatically updated upon clicking "Add Attribute" without re-executing any of those functions.
There is no API for that and I don't think a workaround is possible because when you change an attribute on a current DOM node, the browser is responsible for re-rendering and updating the webpage in a low-level way that is not exposed to the JavaScript context.
Also, keep in mind that any correctly formatted attribute is actually valid in the context of a DOM tree, even though it might not trigger any change at the rendering level or in the way the browser renders the page. Especially the data-* attributes.
There might be some vendor-specific API but that wouldn't be useful if you want cross-browser compatibility.
You need to hardcode it, sadly. Given that you specifically want the SVGElement attributes, maybe you can scrape the W3's SVG standard document to automatically create the list?
Edit: I made a snippet to easily scrape the values from the standard:
const uniq = arr => Array.from(new Set(arr))
const nameElements = document.querySelectorAll('table[summary="Alphabetic list of attributes"] .attr-name')
const arrNameElements = Array.prototype.slice.call(nameElements)
const svgAttributes = uniq(arrNameElements.map(el => el.innerText.replace(/\‘|\’/g, '')))
Just execute it on the svg attributes page, by opening the dev console on the page and pasting in this code :)
Edit 2: I forgot the presentation attributes. I'll let you figure that one out ;)

How to get non-DOM properties of HTML in Javascript

Say a HTML snippet like this:
<div a_example = "x" b_example = "y" class = "z"></div>
What is the proper way to get the corresponding properties of a_example and b_example in Javascript?
Can xpath do the job?
Use getAttribute:
var elem = document.getElementsByClassName("z")[0],
a = elem.getAttribute("a_example");
Here's a working example.
But, as has already been mentioned, you should really be using HTML5 data-* attributes, otherwise your markup is invalid.
Some browsers will add all attributes as named properties of the DOM element, others will only add standard attributes. In both cases you can get non–standard attributes using getAttribute, however such a scheme is not recommended.
It is common to use standard attributes and DOM properties and only use getAttribute where necessary as it is inconsistently implemented in different browsers.
You should take a look at HTML5 data attributes, here is a useful article: http://html5doctor.com/html5-custom-data-attributes/
Reading data attributes from a tag is really easy, and a fallback is available for older browsers. An example from the article:
<div id="sunflower" data-leaves="47" data-plant-height="2.4m"></div>
<script>
// 'Getting' data-attributes using dataset
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;
</script>
If you are using jQuery, it is as simple as saying:
HTML
<div id="testDiv" a_example = "x" b_example = "y" class = "z"></div>
Javascript:
var attr1 = $('#testDiv').attr('a_example');
element.getAttribute(attributename)
This should work for you.
I agree you should look at data attributes and better ways to do add non-standard attributes, but here's a 'raw' answer to your question, but I wouldn't treat this as universally supported (or advisable):
alert(document.getElementsByTagName('div')[0].getAttribute('b_example'));

In DOM is it OK to use .notation for getting/setting attributes?

In DOM, is it OK to refer to an element's attributes like this:
var universe = document.getElementById('universe');
universe.origin = 'big_bang';
universe.creator = null;
universe.style.deterministic = true;
? My deep respect for objects and their privacy, and my sense that things might go terribly wrong if I am not careful, makes me want to do everything more like this:
var universe = document.getElementById('universe');
if(universe.hasAttribute('origin')) then universe.origin = 'big_bang';
etc...
Is it really necessary to use those accessor methods? Of course it may be more or less necessary depending on how certain I am that the elements I am manipulating will have the attributes I expect them to, but in general do the DOM guys consider it OK to use .notation rather than getters and setters?
Thanks!
For XML documents, you must use getAttribute/setAttribute/removeAttribute etc. There is no mapping from JavaScript properties to DOM attributes.
For HTML documents, you can use getAttribute et al to access attributes, but it's best not to because IE6-7 has difficulties with it. The DOM Level 2 HTML properties are not only more reliable, but also easier to read.
It's unclear whether you're using XML or HTML documents here. Clearly origin is not an HTML attribute; ‘custom’ elements and attributes like this should not be included in HTML documents. But it's unclear what universe.style.deterministic refers to; you wouldn't get a CSS style lookup mapped without an HTML style attribute.
Yes, it's fine ;-)
If there's an attribute in the DOM, you can set it or get it, directly.
No private or read-only elements or anything. By the way, JavaScript doesn't have a 'then' keyword.
Due to cross browser issues I always use getAttribute and setAttribute:
if(!universe.getAttribute('origin'))
{
universe.setAttribute('origin', 'big_bang');
}
I don't recall the specifics but I have had problems with the property style universe.origin and dynamically created DOM elements.
No, it's not fine to do so. Most properties of DOM objects can be overwritten. You won't ruin the browser's behavior, since it doesn't use the DOM API. But you will ruin your JS scripts if they attempt to use the overwritten property in its original meaning.
My own way of doing things, when I have several attributes to attach to an object (as opposed to a single flag or link), is to create a custom object and then link it from the DOM element:
var Universe = {
origin: "big_bang",
creator: null,
style: { deterministic: true }
};
document.getElementById('universe')._universe = Universe;

Why doesn't Jquery let me do this

document.getElementById("main").src = '02.jpg';
works
but
$('#main').src = '02.jpg';
doesn't
$("#main").attr("src", "02.jpg");
$('#main') returns a jQuery object, not a HTMLElement, therefore no src property is defined on the jQuery object. You may find this article useful.
Mike has shown one way of setting the src attribute (the way he has shown could probably be considered the most jQuery like way of doing it). A couple of other ways
$("#main")[0].src = '02.jpg';
or
$("#main").get(0).src = '02.jpg';
$('#main').src = '02.jpg';
The jQuery wrapper you get from $(...) does not reproduce all properties and methods of the DOM object(s) it wraps. You have to stick to jQuery-specific methods on the wrapper object: in this case attr as detailed by Mike.
The ‘prototype’ library, in contrast to jQuery, augments existing DOM objects rather than wrapping them. So you get the old methods and properties like .src in addition to the new ones. There are advantages and drawbacks to both approaches.
$("#main") is a collection of matches from a search. document.getElementById("main") is a single DOM element - that does have the src property. Use the attr(x,y) method for when you want to set some attribute on all of the elements in the collection that gets returned by $(x), even if that is only a single element as in getElementById(x).
It's akin to the difference between int and int[] - very different beasts!

How to add/update an attribute to an HTML element using JavaScript?

I'm trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn't work in IE.
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

Categories

Resources