Various DOM-related wrappers (Code Worth Recommending Project)

D

David Mark

Eh? What in the name XPath has to do with HTML? It is a tool traverse
XML documents. OK, I guess it is just too esoteric to ask.

Well, FireFox, Safari and Netscape (and possibly others) use it to
traverse HTML documents. See the samples in this thread.
 
D

David Mark

[snip]


If the function is to be optimized a lot more needs to be done than
that. The CSS selector string should be compiled into a JavaScript
string which represents a function and then that function string is
evaluated. This function can be cached to be used later. This sort of
optimization is really important if selectors with several simple
selectors (e.g. div div div) because those tasks are so much more
laborious. For simple selectors it is not so important.
For example
if (typeof getEBI != 'undefined' &&
typeof getEBTN != 'undefined') {
var getEBCS;
(function() {
//http://elfz.laacz.lv/beautify/
var compile = function(s) {
var m, // regexp matches
tn, // tagName in s
id, // id in s
cn, // className in s
f; // the function body
m = s.match(/^([^#\.]+)/);
tn = m ? m[1] : null;
m = s.match(/#([^\.]+)/);
id = m ? m[1] : null;
m = s.match(/\.([^#]+)/);
cn = m ? m[1] : null;
f = 'var i,els,el,m,ns=[];';
if (id) {
f += 'els=(!d || d.documentElement) ?' +
'((el=getEBI("'+id+'", d)) ? [el] : []) :' +
'getEBTN("'+(tn||'*')+'", d);'
}
else {
f += 'els = getEBTN("'+(tn||'*')+'", d);';
}
f += 'i = els.length;' +
'while (i--) {' +
'el = els;' +
'if (';
if (id) {
f += 'el.id=="'+id+'"';
}
if ((cn||tn) && id) {
f += '&&';
}
if (tn) {
f += 'el.tagName.toLowerCase() == "' + tn + '"';
}
if (cn && tn) {
f += '&&';
}
if (cn) {
f += '((m = el.className) &&' +
'(" "+m+" ").indexOf(" '+cn+' ")>-1)';
}
f += '){' +
'ns[ns.length] = el;' +
'}' +
'}';

f += 'return ns.reverse();';
return new Function('d', f);
}
var cache = {};
getEBCS = function(s, d) {
if (!cache) {


If for some reason a user sends an s that is "toString" then this will
cause a problem. I thought it would be better to use hasOwnProperty.
There is at least one bug with hasOwnProperty in Opera when s is a
number.


Numbers should not be allowed as parameters to this function.
<URL:http://groups.google.com/group/comp.lang.javascript/msg/7ad2adb486fc3f20>

This bug could be worked around by prefixing the selector with a fixed
string.

Are there any other bugs with hasOwnProperty?

I believe it is only supported by modern browsers and IE has some
issues with it (of course.)


It seems to me that "toString" is not a valid selector, so it should
not be passed to this function.

 
D

David Mark

The developer is screwed if the docs say "$(String id) returns DOM
element reference with such ID or null if doesn't exist" - and the
developer is using it to get over it an element by NAME or get
something useful out of say $(undefined); Such developer is screwed by
default and sooner realized it so he will start to read the docs - so
better for him. By compensating rude programming errors up to the last
possibility you do not help anyone: the program will still eventually
fail, but on higher execution level where it will be times more
difficult to find the reason.

You have the wrong end of the stick on this one. I am not
compensating anything as my solution will fail sooner, rather than
later.
If you don't know that then why are you trying to program in
JavaScript anything at all above simple form control helpers?
Theoretically possible someone is still using Windows 3.0 with
Netscape 2.0b (the first one with JavaScript 1.0)

You apparently don't understand feature detection at all.
Again: let's stop that fallacy pretending to program "for the
humanity's past, present and future generations". For _a hell of a
good_ start let's try to cover at least A grade UAs from Yahoo! charthttp://developer.yahoo.com/yui/articles/gbs/

Why? I can write robust Web applications that degrade gracefully in Z-
grade browsers. I am hardly going to take a cue from the YUI
developers on this. As bloated as their code is, they should be able
to do the same.
If your program ever gets any popularity, you'll get a bunch of bug
reports and you'll fix them then.

What program?
If UA doesn't have document.getElementById support then it's NN4 or
older or IE4 or older or something else from the last century. If you

And what would you have an application do when it encounters such an
agent? Degrade gracefully or blunder ahead into the unknown?
really want to make it work on IE4 then I want you to make it work on
NN4 as well as of the same period browser. What the problem? Not
possible? It is possible but extremely ugly and labor intensive. Much
much more labor intensive then ...else if (document.all)... and "look
ma' now how do I care of every possible user!".

On the contrary, that branch allows for the retrieval of an element by
its ID. That is but one feature. Applications that require other
features will have to test those other features. One of the functions
of the API is to make feature testing as simple and concise a process
as possible. Your suggestions indicate that you would prefer to skip
feature testing altogether, which is hardly a realistic option.
 
P

Peter Michaux

I account for that possibility in my getAttribute
wrapper. In other words, this example may look perfectly benign, but
one line can currently throw a script error in IE and the other may in
the future.
var a = document.getElementById('myanchor');
How would the above line throw an error?
If gEBI was not a featured method of the document object or if
document were implemented as an ActiveX object.
I was assuming document.getElementById is available.
If document is an ActiveX object why would it error to call it's
getElementById method?
if (a.href) { ... }
I assume this is the same error that would occur in the first "if" of
your post above if document.getElementById was an ActiveX object.
If document was an ActiveX object. The error occurs when [[Get]] is
called on methods of ActiveX objects, not on the objects themselves.
I'm lost.
If document is present and an ActiveX and has a getElementById
property, what you are saying is the following line will error
if (document.getElementById)
Yep.



If document is present and an ActiveX and has a getElementById
property, what will happen in the next line? I hope not an error
because then there would be no point in having methods on an ActiveX
object
document.getElementById('foo')

No problem there. That invokes the internal [[Call]] method, not
[[Get]]. Try this out with window.external.addFavorite.

Thanks. I get it.
 
D

David Mark


It seems to me that "toString" is not a valid selector, so it should
not be passed to this function.

I was thinking about and XML document where the tag names could be
anything.


I thought you maybe that was what you were getting at, but it seemed
to me that XML documents (other than XHTML) were out of the scope of
this project at the moment. Regardless, the XPath branch can be
augmented to work with IE when the passed document is XML. I have the
code for that, but cropped it out as I figured it was too much to
consider anything but (X)HTML at the moment.
 
T

Thomas 'PointedEars' Lahn

VK said:
You may want to update your data: IE supports XPath for the last 8
years at least.

Since the XPath 1.0 Specification is dated 1999-11-16 CE, at least
your "at least" is not likely. [1] In fact, the MSDN Library says that
IXMLDOMNode::selectNodes() was not implemented before MSXML 3.0. [2]
That would place the first support for *client-side* XPath *scripting*
in IE 6.0 (2001-08-27), whereas you would place it in version 5.0
(1999-03-18) and before. [3]


PointedEars
___________
[1] http://www.w3.org/TR/1999/REC-xpath-19991116
[2] http://msdn2.microsoft.com/en-us/library/ms754523.aspx
[3] http://en.wikipedia.org/wiki/Internet_Explorer#Version_history
 
T

Thomas 'PointedEars' Lahn

VK said:
Eh? What in the name XPath has to do with HTML? It is a tool traverse
XML documents. OK, I guess it is just too esoteric to ask.

Although primarily intended for XML documents, XPath can be applied to
Valid HTML documents as well. Here's a snippet from my DOM library [1]:

this.getElemByTagName = this.gEBTN = (function dhtml_getElemByTagName()
{
if (this.isMethodType(typeof document.evaluate) && document.evaluate)
{
// W3C DOM Level 3 XPath
return function dhtml_getElemByTagName(s, i)
{
if (!s)
{
s = '*';
}

var result = document.evaluate('//' + s, document, null, 0, null);
if (result)
{
var found = [], res;
while ((res = result.iterateNext()))
{
found.push(res);
}

if (!isNaN(i) && i > -1)
{
result = found;
}
else
{
result = found;
}
}

return result;
};
}
...
}

But as David Mark has stated correctly, IE does not support that in HTML,
neither this way nor with selectNodes().


PointedEars
___________
[1] http://PointedEars.de/scripts/dhtml.js
 
P

Peter Michaux

Eh? What in the name XPath has to do with HTML? It is a tool traverse
XML documents. OK, I guess it is just too esoteric to ask.

Although primarily intended for XML documents, XPath can be applied to
Valid HTML documents as well. Here's a snippet from my DOM library [1]:

this.getElemByTagName = this.gEBTN = (function dhtml_getElemByTagName()
{
if (this.isMethodType(typeof document.evaluate) && document.evaluate)

Would you mind posting your isMethodType function?

What is the need for "&& document.evaluate" ?
{
// W3C DOM Level 3 XPath
return function dhtml_getElemByTagName(s, i)
{
if (!s)
{
s = '*';
}

var result = document.evaluate('//' + s, document, null, 0, null);
if (result)
{
var found = [], res;
while ((res = result.iterateNext()))
{
found.push(res);
}

if (!isNaN(i) && i > -1)
{
result = found;
}
else
{
result = found;
}
}

return result;


Why bother with this return if there was no result? The mozilla
documentation

<URL: http://developer.mozilla.org/en/docs/DOM:document.evaluate>

does not describe what an "XPathResult" is.

};
}
...
}

[snip]

Thanks.
 
P

Peter Michaux

cache = compile(s);
It seems to me that "toString" is not a valid selector, so it should
not be passed to this function.

I was thinking about and XML document where the tag names could be
anything.

I thought you maybe that was what you were getting at, but it seemed
to me that XML documents (other than XHTML) were out of the scope of
this project at the moment.


I certainly don't think a web page should be written in XHTML.

What I was thinking was an xml document may be the result of and
XMLHttpRequest.
Regardless, the XPath branch can be
augmented to work with IE when the passed document is XML. I have the
code for that, but cropped it out as I figured it was too much to
consider anything but (X)HTML at the moment.

Is it much code?

Peter
 
P

Peter Michaux

And revisiting the feature test argument from a few posts back, I
really thing that isFeaturedMethod should be used,
Why not just "isMethod"? It is always testing a function property of
an object which is called a method. This isFeaturedMethod gets
plastered all over the place and if "isMethod" is sufficient then I
always like shorter.

Fine by me. It is only for appropriate for testing methods of host
objects (which are the only ones that IE considers of type 'object.')
I called it "isFeaturedMethod" to make it clear that it was for
feature testing the host environment.

I think isHostMethod is probably better because an plain JavaScript
object could "feature" a method. "featured" is a bit ambiguous.

The documentation should note that
1) the first argument must be qualified host object
2) the second argument is the name of a property that the developer
expects to be a callable
3) if the function returns true then it is pretty safe to assume it
that the method can be called on the object

Would it be possible to remove the word "host" from rule #1? If so the
name could change to isMethod.

What a huge mass of posts to plow through over this! Thanks for the
patients as I caught up. I thought I could avoid reading the bickering
but I had to do it in the end.
 
T

Thomas 'PointedEars' Lahn

Peter said:
VK said:
The most popular browser, still by a long shot, is IE which doesn't
have XPath.
You may want to update your data: IE supports XPath for the last 8
years at least.
Not for HTML documents.
Eh? What in the name XPath has to do with HTML? It is a tool traverse
XML documents. OK, I guess it is just too esoteric to ask.
Although primarily intended for XML documents, XPath can be applied to
Valid HTML documents as well. Here's a snippet from my DOM library [1]:

this.getElemByTagName = this.gEBTN = (function dhtml_getElemByTagName()
{
if (this.isMethodType(typeof document.evaluate) && document.evaluate)

Would you mind posting your isMethodType function?

Yes, as it is readily available e.g. via Google Web Search and Google
Groups Search. I must have posted it a dozen times or so here and in
de.comp.lang.javascript. Note that it is part of a GPL'd library.
What is the need for "&& document.evaluate" ?

I have also explained that several times before: As isMethodType() is only
passed the string result of the `typeof' operation, which can be `object',
another test is necessary to determine that the value is not `null'.
{
// W3C DOM Level 3 XPath
return function dhtml_getElemByTagName(s, i)
{
if (!s)
{
s = '*';
}

var result = document.evaluate('//' + s, document, null, 0, null);
if (result)
{
var found = [], res;
while ((res = result.iterateNext()))
{
found.push(res);
}

if (!isNaN(i) && i > -1)
{
result = found;
}
else
{
result = found;
}
}

return result;


Why bother with this return if there was no result?


If document.evaluate() is implemented as specified in DOM Level 3 XPath,
then there is always a result (unless the XPath expression is invalid);
a reference to an object that implements the XPathResult interface.
However, if it is implemented differently, I want the method to return
the implementation's false-value then.
The mozilla documentation

<URL: http://developer.mozilla.org/en/docs/DOM:document.evaluate>

does not describe what an "XPathResult" is.

Yes, it does. Follow the link at the bottom.
[...]
Thanks.

What for, exactly?


PointedEars
 
R

RobG

Peter said:
VK wrote:
The most popular browser, still by a long shot, is IE which doesn't
have XPath.
You may want to update your data: IE supports XPath for the last 8
years at least.
Not for HTML documents.
Eh? What in the name XPath has to do with HTML? It is a tool traverse
XML documents. OK, I guess it is just too esoteric to ask.
Although primarily intended for XML documents, XPath can be applied to
Valid HTML documents as well. Here's a snippet from my DOM library [1]:
this.getElemByTagName = this.gEBTN = (function dhtml_getElemByTagName()
{
if (this.isMethodType(typeof document.evaluate) && document.evaluate)
Would you mind posting your isMethodType function?

Yes, as it is readily available e.g. via Google Web Search and Google
Groups Search. I must have posted it a dozen times or so here and in
de.comp.lang.javascript. Note that it is part of a GPL'd library.
What is the need for "&& document.evaluate" ?

I have also explained that several times before: As isMethodType() is only
passed the string result of the `typeof' operation, which can be `object',
another test is necessary to determine that the value is not `null'.
[...]

It seems to me that the various "code worth recommending project"
threads have accumulated several hundred posts mostly between 3 or 4
posters. Much good information has been noted, but is now mired in
various threads and threads-within-threads.

I think that the wikki component of the repository should be brought
into play as a place to put the results of discussion so far. I
volunteered as a contributor to the wikki part, but unfortunately have
not had time to do much about it yet - I've started on a feature
detection article based on filtering through the various "when is a
function not a function" threads, but it will take a little longer
yet.

It would help if discussions were approached in a similar manner to
the FAQ, that is, someone proposes the text that should be published,
then others can provide comments and proposed changes. Once it gets
to a reasonable state, it can be published. It might also be OK to
publish an article as DRAFT, and for it to be taken to version 1.0 (or
similar) when there is sufficient agreement on its content. Clearly
this newsgroup is not the place to publish, but to make announcements
that an article has been published and comment is requested.

I'd also like to hear from others if they think the discussions should
be held elsewhere with only the salient points raised here - much like
other groups where a core discussion group focuses on a particular
topic or theme away from the general community.
 
P

Peter Michaux

[snip]
It seems to me that the various "code worth recommending project"
threads have accumulated several hundred posts mostly between 3 or 4
posters. Much good information has been noted, but is now mired in
various threads and threads-within-threads.

Lots to wade through!

I think that the wikki component of the repository should be brought
into play as a place to put the results of discussion so far.

I agree.

I
volunteered as a contributor to the wikki part, but unfortunately have
not had time to do much about it yet - I've started on a feature
detection article based on filtering through the various "when is a
function not a function" threads, but it will take a little longer
yet.

That is great.

There is also the article about feature detection on the jibbering
site to consider.
It would help if discussions were approached in a similar manner to
the FAQ, that is, someone proposes the text that should be published,
then others can provide comments and proposed changes. Once it gets
to a reasonable state, it can be published. It might also be OK to
publish an article as DRAFT, and for it to be taken to version 1.0 (or
similar) when there is sufficient agreement on its content. Clearly
this newsgroup is not the place to publish, but to make announcements
that an article has been published and comment is requested.

I'd also like to hear from others if they think the discussions should
be held elsewhere with only the salient points raised here - much like
other groups where a core discussion group focuses on a particular
topic or theme away from the general community.

I think discussion should be held in the group.

It isn't necessary to get the process perfect on the first try.
 
P

Peter Michaux

[snip]
if (typeof getEBI != 'undefined' &&
typeof getEBTN != 'undefined') {

Looking at the above I'm a little puzzled why I wrote it that way.

It seems the following would be a better test

if (typeof getEBI == 'function' &&
typeof getEBTN == 'function') {

Any problem with this?

(I can't even believe I'm wondering about this but with all the recent
fuss I thought I'd ask.)
 
D

Dr J R Stockton

In comp.lang.javascript message <45cfaa54-8670-4472-b3a6-ec14838231d3@e1
0g2000prf.googlegroups.com>, Tue, 11 Dec 2007 12:04:25, VK
If UA doesn't have document.getElementById support then it's NN4 or
older or IE4 or older or something else from the last century. If you
really want to make it work on IE4 then I want you to make it work on
NN4 as well as of the same period browser.

If the facts (below) are as I believe, then that's false logic (if not
natural perversity).

(1) IE4, being distributed with Win98, was and is more widely used than
NN4.
(2) Support for IE4 is, for at least one common task, easier than for
NN4.
 
D

David Mark

[snip]


if (typeof getEBI != 'undefined' &&
typeof getEBTN != 'undefined') {

Looking at the above I'm a little puzzled why I wrote it that way.

Probably because you were testing for variables created in the same
script. But of course, it may not be created at all and it would be
possible for another script to define them as something other than
functions.
It seems the following would be a better test

if (typeof getEBI == 'function' &&
typeof getEBTN == 'function') {

This is more robust.
 
D

David Mark

[snip]
It seems to me that the various "code worth recommending project"
threads have accumulated several hundred posts mostly between 3 or 4
posters. Much good information has been noted, but is now mired in
various threads and threads-within-threads.

Yes, the thinking leading up to the creation of the various functions
settled on so far is not particularly accessible.
I think that the wikki component of the repository should be brought

Wiki? I can't remember what that stands for (if anything.)
into play as a place to put the results of discussion so far. I
volunteered as a contributor to the wikki part, but unfortunately have
not had time to do much about it yet - I've started on a feature
detection article based on filtering through the various "when is a
function not a function" threads, but it will take a little longer
yet.

It would be nice to have articles that summarize the discussions in
the wiki.
It would help if discussions were approached in a similar manner to
the FAQ, that is, someone proposes the text that should be published,
then others can provide comments and proposed changes. Once it gets
to a reasonable state, it can be published. It might also be OK to
publish an article as DRAFT, and for it to be taken to version 1.0 (or
similar) when there is sufficient agreement on its content. Clearly
this newsgroup is not the place to publish, but to make announcements
that an article has been published and comment is requested.

From what I understand, all proposed code is to be published and
discussed here, but I agree that that might not be the best strategy.
For one, the text wrapping issue is annoying.
I'd also like to hear from others if they think the discussions should
be held elsewhere with only the salient points raised here - much like
other groups where a core discussion group focuses on a particular
topic or theme away from the general community.

Makes sense to me.
 
D

David Mark

l = r.snapshotLength;
while (l--) { q[l] = r[l]; }

Testing my updated version of this, it appears something got lost in
translation when I spliced this together. This line should clearly
be:

while (l--) { q[l] = r.snapshotItem(l); }

I know I tested this, but I don't see how it would have worked at all
without this fix. I must have changed something before I posted it.
Regardless, this is the proper syntax.
 
R

Richard Cornford

RobG wrote:
It seems to me that the various "code worth recommending
project" threads have accumulated several hundred posts
mostly between 3 or 4 posters. Much good information has
been noted, but is now mired in various threads and
threads-within-threads.

That was probably inevitable with the first few examples. It is a good
idea that these things are kicked around a bit in public. And people
will want to state opinions, question definitions and raise points.

With the possible exception of people who want to be deliberately
obtuse/disruptive the likelihood is that much that is under debate now
will settle down with compromise or agreements to disagree. Peter is
trying to formalize the compromises into statements about the starting
points for design/development. And part of the point of the 'multiple
implementations' of layered interfaces design is that it can accommodate
differing attitudes towards some browser scripting principles.

So even if a base position of not worrying about actively
supporting/accommodating browsers as old as IE and Netscape 4 is
employed there is no reason for the repository not to include (properly
documented) implementation versions that do accommodate those browsers
(any less that it would be acceptable for it to include implementations
for much more restrictive contexts such as browser specific Intranets
and web applications that specify a very small set of browsers (with the
motivation that those applications be OS neutral but may require
specific browsers on each OS)).
I think that the wikki component of the repository should
be brought into play as a place to put the results of
discussion so far. I volunteered as a contributor to the
wikki part, but unfortunately have not had time to do much
about it yet - I've started on a feature detection article
based on filtering through the various "when is a function
not a function" threads, but it will take a little longer
yet.

Does that mean that you have come to some conclusion as to what is, and
what is not, a 'function'?

Personally I think wikis are far more trouble than they are worth. And
they are pretty much useless off-line.
It would help if discussions were approached in a similar
manner to the FAQ, that is, someone proposes the text that
should be published, then others can provide comments and
proposed changes.

So far there does seem be a deficit in proposals being explicit about
what the interface being created is supposed to do up front. That seems
unfortunate as when a system is based around interface design with
multiple underlying implementations then it seems unreasonable to have
to deduce how a second implementation should behave from examining the
actual behaviour of the first (not to mention the question of
determining if the first implementation is correct without a clear
assertion of what "correct" behaviour is expected to be).

Clearly this newsgroup is not the place to publish, but to
make announcements that an article has been published and
comment is requested.

I strongly disagree with that. If something is to be "Code Worth
Recommending" then who is supposed to be recommending it, and why? If
there is some notion that the end result be "Recommended" by this group
then that end result must be presented to this group, and the whole
group (regular and intermittent participants, lurkers, casual visitors
and anyone stumbling across posts as a result of web searches). It is
the strength of this group that it is public, unmoderated and open to
anyone.
I'd also like to hear from others if they think the
discussions should be held elsewhere with only the salient
points raised here - much like other groups where a core
discussion group focuses on a particular topic or theme
away from the general community.

There can never be anything to stop additional discussion happening
elsewhere. It is extremely unlikely that I would bother to participate
in such discussions.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top