473,898 Members | 2,767 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getAttribute question

I have always accessed attributes such as disabled using the DOM
element property, however I was wondering about implementing a more
generic function to get the values of attributes - which of course
leads to the DOM Element Interface's getAttribute method:

<URL: http://www.w3.org/TR/DOM-Level-2-Cor...ml#ID-666EE0F9 >

The DOM 2 Core specification says that getAttribute should return the
value of an attribute as a string, however attributes such as
disabled, checked, readonly, etc. don't have values specified in the
HTML specification, it just specifies a behaviour if the attribute is
present or not. The DOM HTML spec says that such attributes should
return true or false, e.g. Inteface HTMLInputElemen t:

<URL: http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-50886781 >

My interpretation is that if the attribute is accessed as a property
of a DOM element (e.g. someElement.dis abled), it should return:

1. boolean true if the element has the attribute set in the markup
or
it has been set to true by script
2. boolean false only if the attribute value has been set to false
by script
3. null if the attribute is not in the markup and hasn't been set by
script,
or if the element doesn't support the attribute

That way the value of the DOM property can be easily converted to an
equivalent string simply by using the returned object's toString
method ('true', 'false' and '' respectively) which seems to fit the
specification for getAttribute.

I don't know of a browser that behaves as described above, they all
have foibles. If I were to write a generic getAttributeVal ue
function, should it behave as described above, or should it instead
return 'disabled', '' and '' respectively? The logic could then be
applied to other "no value" attributes such as checked, readonly and
selected. Condition statements could be:

if (el.getAttribut eValue('disable d') == 'true') { ... }

which is reasonably consistent with:

if (el.disabled) { ... }

What do others think?
--
Rob
Jun 27 '08 #1
4 2890
RobG schreef:
The DOM 2 Core specification says that getAttribute should return the
value of an attribute as a string, however attributes such as
disabled, checked, readonly, etc. don't have values specified in the
HTML specification, it just specifies a behaviour if the attribute is
present or not. The DOM HTML spec says that such attributes should
return true or false, e.g. Inteface HTMLInputElemen t:
The common way to specify this according to the current standards is:

<... disabled="disab led"/>

Browsers will parse this the same way as the old notation.
JW
Jun 27 '08 #2
RobG wrote:
I have always accessed attributes such as disabled using the DOM
element property, however I was wondering about implementing a more
generic function to get the values of attributes - which of course
leads to the DOM Element Interface's getAttribute method:

<URL: http://www.w3.org/TR/DOM-Level-2-Cor...ml#ID-666EE0F9 >
Not necessarily. ECMAScript implementations provide the bracket property
accessor to use variable string values as property names, and the number of
element properties that do not match the lowercase versions of their
attribute name is limited.

See also http://pointedears.de/scripts/dhtml.js:setAttr()
The DOM 2 Core specification says that getAttribute should return the
value of an attribute as a string, however attributes such as
disabled, checked, readonly, etc. don't have values specified in the
HTML specification,
Yes, they have.
it just specifies a behaviour if the attribute is present or not.
Not true:

http://www.w3.org/TR/html401/intro/s...html#h-3.3.4.2
The DOM HTML spec says that such attributes should
return true or false, e.g. Inteface HTMLInputElemen t:

<URL: http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-50886781 >

My interpretation is that if the attribute is accessed as a property
of a DOM element (e.g. someElement.dis abled), it should return:

1. boolean true if the element has the attribute set in the markup
or
it has been set to true by script
2. boolean false only if the attribute value has been set to false
by script
3. null if the attribute is not in the markup and hasn't been set by
script,
or if the element doesn't support the attribute
Correct.
That way the value of the DOM property can be easily converted to an
equivalent string simply by using the returned object's toString
method ('true', 'false' and '' respectively) which seems to fit the
specification for getAttribute.
Yes, you could. However, this is what setAttribute() is for.
I don't know of a browser that behaves as described above, they all
have foibles. If I were to write a generic getAttributeVal ue
function, should it behave as described above,
It should not return boolean values as content of string values.
or should it instead return 'disabled', '' and '' respectively? The
logic could then be applied to other "no value" attributes such as
checked, readonly and selected. Condition statements could be:

if (el.getAttribut eValue('disable d') == 'true') { ... }

which is reasonably consistent with:

if (el.disabled) { ... }

What do others think?
You should implement

if (_getAttributeV alue(el, 'disabled'))

if you don't like

if (el.getAttribut e('disabled').t oLowerCase() == 'disabled')

already. As you should know by now, host objects should not be tried
to be augmented, and they cannot be prototyped universally.
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Jun 27 '08 #3
On May 8, 10:54 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
RobG wrote:
I have always accessed attributes such as disabled using the DOM
element property, however I was wondering about implementing a more
generic function to get the values of attributes - which of course
leads to the DOM Element Interface's getAttribute method:
<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9>

Not necessarily. ECMAScript implementations provide the bracket property
accessor to use variable string values as property names, and the number of
element properties that do not match the lowercase versions of their
attribute name is limited.

See alsohttp://pointedears.de/scripts/dhtml.js:setAtt r()
I'm interested in your mapping of char to ch, why is that? I noted an
oddity with IE that getAttribute('c h') returns an empty string if the
attribute isn't present when it should return null.

Also you have:

colSpan: "colSpan",

should the property name have a lower case 's'?

The DOM 2 Core specification says that getAttribute should return the
value of an attribute as a string, however attributes such as
disabled, checked, readonly, etc. don't have values specified in the
HTML specification,

Yes, they have.
it just specifies a behaviour if the attribute is present or not.

Not true:

http://www.w3.org/TR/html401/intro/s...html#h-3.3.4.2
Thanks, it would have been nice if a reference to that was included in
appropriate places in the HTML 4 and DOM HTML specifications.

The DOM HTML spec says that such attributes should
return true or false, e.g. Inteface HTMLInputElemen t:
<URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-50886781>
My interpretation is that if the attribute is accessed as a property
of a DOM element (e.g. someElement.dis abled), it should return:
1. boolean true if the element has the attribute set in the markup
or
it has been set to true by script
2. boolean false only if the attribute value has been set to false
by script
3. null if the attribute is not in the markup and hasn't been set by
script,
or if the element doesn't support the attribute

Correct.
That way the value of the DOM property can be easily converted to an
equivalent string simply by using the returned object's toString
method ('true', 'false' and '' respectively) which seems to fit the
specification for getAttribute.

Yes, you could. However, this is what setAttribute() is for.
I don't know of a browser that behaves as described above, they all
have foibles. If I were to write a generic getAttributeVal ue
function, should it behave as described above,

It should not return boolean values as content of string values.
It could return the object's toString value rather than the object.
>
or should it instead return 'disabled', '' and '' respectively? The
logic could then be applied to other "no value" attributes such as
checked, readonly and selected. Condition statements could be:
if (el.getAttribut eValue('disable d') == 'true') { ... }
which is reasonably consistent with:
if (el.disabled) { ... }
What do others think?

You should implement

if (_getAttributeV alue(el, 'disabled'))

if you don't like

if (el.getAttribut e('disabled').t oLowerCase() == 'disabled')

already. As you should know by now, host objects should not be tried
to be augmented, and they cannot be prototyped universally.
I wasn't suggesting augmenting host objects, I was just looking for a
consistent way to get attribute values. The following function seems
to do the trick, I haven't tested it widely yet. It has an issue with
IE and attributes named 'ch', I await your response from the question
above.
function getAttributeVal ue(element, attribute)
{
var v, lowerAtt,
htmlFlags = {
checked: 'checked',
compact: 'compact', // deprecated HTML 4
declare: 'declare',
defer: 'defer',
disabled: 'disabled',
ismap: 'ismap',
multiple: 'multiple',
nohref: 'nohref',
noresize: 'noresize',
noshade: 'noshade',
nowrap: 'nowrap', // deprecated HTML 4
readonly: 'readonly',
selected: 'selected'
},
mapFwd = {
alink: 'aLink',
accesskey: 'accessKey',
bgcolor: 'bgColor',
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
'char': 'ch',
charoff: 'chOff',
'class': 'className',
codebase: 'codeBase',
codetype: 'codeType',
colspan: 'colSpan',
datetime: 'dateTime',
frameborder: 'frameBorder',
'for': 'htmlFor',
ismap: 'isMap',
longdesc: 'longDesc',
maxlength: 'maxLength',
marginheight:'m arginHeight',
marginwidth: 'marginWidth',
nohref: 'noHref',
noresize: 'noResize',
noshade: 'noShade',
nowrap: 'noWrap',
readonly: 'readOnly',
rowspan: 'rowSpan',
tabindex: 'tabIndex',
usemap: 'useMap',
valuetype: 'valueType',
vlink: 'vLink'
},
mapRev = {
classname: 'class',
// ch: 'char',
htmlfor: 'for'
};

if (typeof attribute == 'string') {
lowerAtt = attribute.toLow erCase();

if (lowerAtt in htmlFlags) {
return !!element[attribute]? htmlFlags[lowerAtt] : '';
}

v = element.getAttr ibute(attribute );

if (v === null) {
v = element.getAttr ibute(mapFwd[lowerAtt]);
}

if (v === null) {
v = element.getAttr ibute(mapRev[lowerAtt]);
}

return v;
}
}
--
Rob
Jun 27 '08 #4
RobG wrote:
[...] Thomas 'PointedEars' Lahn [...] wrote:
>RobG wrote:
>>I have always accessed attributes such as disabled using the DOM
element property, however I was wondering about implementing a more
generic function to get the values of attributes - which of course
leads to the DOM Element Interface's getAttribute method:
<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9>
Not necessarily. ECMAScript implementations provide the bracket property
accessor to use variable string values as property names, and the number of
element properties that do not match the lowercase versions of their
attribute name is limited.

See alsohttp://pointedears.de/scripts/dhtml.js:setAtt r()
(Eeek, Google Groups posting.)
I'm interested in your mapping of char to ch, why is that?
The `char' attribute of HTML 4.01 `COL', `COLGROUP', `TBODY', `TD', `TFOOT',
`TH', `THEAD', and `TR' elements, and their lowercase XHTML 1.0 correlates,
is represented by the `ch' attribute of the HTMLTableColEle ment,
HTMLTableSectio nElement, HTMLTableCellEl ement, and HTMLTableRowEle ment
interfaces of W3C DOM Level 2 HTML, and the `ch' property of the objects
implementing these, respectively.

http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-84150186
http://www.w3.org/TR/DOM-Level-2-HTM...t-binding.html
I noted an oddity with IE that getAttribute('c h') returns an empty string if the
attribute isn't present when it should return null.
However, this is unsurprising, as it should have been getAttribute('c har').
Also you have:

colSpan: "colSpan",

should the property name have a lower case 's'?
Yes, it should. It had been fixed already in the local version (currently
0.9.4.200804232 1), but thanks anyway.
>>I don't know of a browser that behaves as described above, they all
have foibles. If I were to write a generic getAttributeVal ue
function, should it behave as described above,
It should not return boolean values as content of string values.

It could return the object's toString value rather than the object.
Which object are you talking about? We are dealing with *primitive values*
here. So if a method is to return the value of a boolean HTML attribute,
there are two implementations I would consider reasonable: Either a) return
the *boolean* values `true' or `false', or b) return the proper attribute
values as strings, i.e. e.g. "disabled" if set and "" if not set. Either
way, it should be easy to use the return value in a conditional expression,
which both proposed implementations would accomplish.
>>or should it instead return 'disabled', '' and '' respectively? The
logic could then be applied to other "no value" attributes such as
checked, readonly and selected. Condition statements could be:
if (el.getAttribut eValue('disable d') == 'true') { ... }
which is reasonably consistent with:
if (el.disabled) { ... }
What do others think?
You should implement

if (_getAttributeV alue(el, 'disabled'))

if you don't like

if (el.getAttribut e('disabled').t oLowerCase() == 'disabled')

already. As you should know by now, host objects should not be tried
to be augmented, and they cannot be prototyped universally.

I wasn't suggesting augmenting host objects, I was just looking for a
consistent way to get attribute values.
But el.getAttribute Value() is suggesting host object augmentation, is it not?
[...]
function getAttributeVal ue(element, attribute)
{
var v, lowerAtt,
htmlFlags = {
checked: 'checked',
compact: 'compact', // deprecated HTML 4
declare: 'declare',
defer: 'defer',
disabled: 'disabled',
ismap: 'ismap',
multiple: 'multiple',
nohref: 'nohref',
noresize: 'noresize',
noshade: 'noshade',
nowrap: 'nowrap', // deprecated HTML 4
readonly: 'readonly',
selected: 'selected'
},
There really is no need for `htmlFlags'.
mapFwd = {
[...]
},
ACK. This is also what I have.
mapRev = {
classname: 'class',
// ch: 'char',
htmlfor: 'for'
};
Why do you consider this necessary? Are we talking HTML attributes or not?
if (typeof attribute == 'string') {
This is not required, and unnecessarily limits the ways this method may be
applied.
lowerAtt = attribute.toLow erCase();
I understand you test for the string type above because of this assignment,
however any value can be converted to string easily:

lowerAtt = String(attribut e).toLowerCase( );

(attribute.toSt ring() is not always feasible.)
if (lowerAtt in htmlFlags) {
For reasons I mentioned before, the `in' operator should be avoided outside
`for..in' statements for the time being.
return !!element[attribute]? htmlFlags[lowerAtt] : '';
While written more conveniently, the test accesses a property of a host
object without testing for it first which is considered error-prone.
}

v = element.getAttr ibute(attribute );
Much the same here.
if (v === null) {
v = element.getAttr ibute(mapFwd[lowerAtt]);
}

if (v === null) {
v = element.getAttr ibute(mapRev[lowerAtt]);
}
Your assertions are not supported by the W3C DOM Level 2 and 3 Core
Specifications. According to these, Element::getAtt ribute() never returns
`null'. Faulty implementations do not justify your deliberately violating
the standard yourself. So the least you have to consider instead is

if (!v)
{
return v;
}
}

Regards,

PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1828
by: David | last post by:
Hi, I'm trying to parse an xml file and am a bit confused. I have created my class XmlParser. Also I have 3 other questions. 1-How to the GetAttribute to search for the value of a specific pattern ? I want to get the value of the Count tag. 2- My file does not contain the standalone header ? How can I deal with
1
4749
by: mr_burns | last post by:
Hi, I have the following code that works fine except the getAttribute line: var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.load("note.xml"); nodes = xmlDoc.documentElement.childNodes; text = '<p>note:<br>';
3
21931
by: hutch | last post by:
Hi, I'm making use of this VERY useful function for a so called 'standards compliant' replacement for target="_blank": function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for (var i=0; i<anchors.length; i++) { var anchor = anchors;
6
10027
by: Banski | last post by:
Hi, Im quite new to XML in .Net. Im getting values from an xml file using XPath and sorting as you see in the code below. I cant figure out how to get the value of date with GetAttribute. Hope that this short description if enough and you can help to sort out this problem. Thanks in advance banski
2
7635
by: DN | last post by:
This works: nav.GetAttribute("@ATTRIBUTE",""); This doesn't: string strTemp = "@ATTRIBUTE"; nav.GetAttribute(strTemp,""); Anybody know a way around this?
3
3483
by: duff | last post by:
Hiya, I'm trying to replace the commented out code below with a neater version using the IAttributeAccessor interface (so that I don't have to write 'if' statements for all control types). At the moment this doen't work. The test line I put in (string s = ControlAttributes.string s = ControlAttributes.GetAttribute ("Text");
13
3244
by: Noa | last post by:
Hi I have a page that looks like that: <form name="kuku1" action ="anotherpage.html" > <input name="name"> <input name="kuku2"> </form> As far as i know, "getAttribute" should return a string value of an
2
5856
by: christopher.secord | last post by:
I'm having a hard time understanding an error that I'm getting. In the code below, I'm trying to call substring() on an attribute of an anchor. The error I get says "getAttribute("rel") has no properties" The reason this confuses me is that getAttribute("rel") returns a string, so it should have all the properties and methods of a string, right?? What am I missing here? - chris
3
2567
by: maminx | last post by:
I have this script... var td = document.createElement('td'); var p = document.createElement('p'); var label = document.createElement('label'); var span = document.createElement('span'); var theData = document.createTextNode('Chart Of Account'); var theSelect = document.createElement('select'); theSelect.setAttribute('name', 'items'); var opCol = document.createElement('option');
0
9993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10857
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9658
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8034
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7187
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5877
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4705
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3303
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.