View Full Version : Attribute Default Value

Rain Lover
07-23-2014, 07:12 AM
Can you get an attribute default value so you don't have to repeat it in the following example:

<p title="foo" id="p">Hello, world!</p>
<input type="text" id="i">
var p = document.getElementById('p'),
i = document.getElementById('i');
i.oninput = function () {
p.title = this.value;
if (this.value == 'bar') {
p.title = 'foo';

DEMO (http://jsfiddle.net/jU5Tv/)

Is there something like p.title = p.title.defaultValue as we use for text fields?

07-23-2014, 06:38 PM
Nope. You could save the value then recall it later. Also, as a point of information, since p.title is a string, it can only have the prototypical properties and functions of a string, like length, anchor(), etc. You cannot create a property for it - say p.title.defaultValue, like you could if it were an object. You could store its beginning value in another attribute for the element because the element is an object. HTML 5 is the most standard for doing something like that:

<p title="foo" id="p">Hello, world!</p>
var p = document.getElementById('p');
p.setAttribute('data-beginningTitle', p.title);

Once you have that much, you can access the original title of p anytime by:


Resetting it to its beginning value would be done like so:

p.title = p.getAttribute('data-beginningTitle');

But you could just as easily save the original value of p.title to a global variable or a property of some other object, or as a variable in some limited yet sufficient scope to achieve retrieval as needed.