Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Javascript selector engines and built in functions

I have found the following tutorial on creating a selector engine.. http://blog.insicdesigns.com/2010/04/creating-your-own-selector-engine/

In javascript we have functions like

etc,.....But for the same functionality,in their selector engine,they are doing checks like

 this.nodes[i].tagName == nm.toUpperCase() 

instead of getElementsByTagName.What is the advantage of this approach?...

Also what is the usage of assigning all nodes to a vairiable using

 e.getElementsByTagName('*');

Upvotes: 0

Views: 260

Answers (3)

Joseph
Joseph

Reputation: 119837

There is an inconsistency when you get the tagName property of elements. Some browsers return uppercase and others lowercase. To normalize the output of the value, you have to do one or the other before continuing further operation.

As for e.getElementsByTagName('*');, i recently answered a question where the OP wants to find ALL elements containing an attribute name which has a prefix mce_. The only way to get such elements is to get all elements in the DOM, and inspect their attribute names.

There is also a good application of this getElementsByTagName('*') and that is determining the direct child of an element. For instance, in a very deep DOM. If I were to find certain parent elements based on an attribute and get it's children, normally you would do a recursive search from body downwards to find the parent. This would take a lot of recursive operations. Afterwards, you determine their children.

Another way to do it is to get all tags, determine their parent node, and if they have the parent with the attribute, they are the direct child. This method requires no recursion, only getElementsByTagName('*') and a loop through the nodeList that was returned.

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

The following line

this.nodes[i].tagName == nm.toUpperCase() 

Is within the function ofTag. It's filtering a set of nodes looking for nodes with the given name.

The next line

e.getElementsByTagName('*');

Retrieves all the children/descendants under a node so you can later filter it like the following

new DOMNodes(Selector.getAll(document)).ofTag('p').hasClass('note');  

Upvotes: 1

rlemon
rlemon

Reputation: 17666

this.nodes[i].tagName == nm.toUpperCase() is part of a method to filter the list of nodes by tag name.... so nothing to do with 'getting elements by their tag name'

the last point is not a real question.. you want to know reasons for "why would you select all nodes"? well you are writing a sector engine....

Upvotes: 1

Related Questions