JavaScript DOM Chapter 4 getElementByTagNames

Source: Internet
Author: User

GetElementByTagNames (names in the plural number) obtains some tag elements and stores them in an array in their order. This is very useful. For example, in the TOCScript in the previous chapter, you need to obtain all H3 and H4 in the entire article.
I very much want to add this function to the node prototype, but it does not work in IE and Safari. So he can only be treated as a common function.

Use
GetElementByTagNames has two parameters:
1. A tag Name string separated by commas.
2. An optional start element. If the tag exists, search for the tags in the sub-element of the element. If the tag does not exist, search for the tags in the entire document.
This function returns an array (rather than a node list) based on the required tag name, in the order they appear in the source code. The browser supports sourceIndex or compareDocumentPosition for sorting. If none of them support (Safari), the order of tag names when the getElementByTagNames () function is called.
Instance 1Copy codeThe Code is as follows: var headerList = getElementsByTagNames ('h1, h2, h3, h4 ');

Now headerList is an array of H1-H4 contained in the document, sorted in the order they appear.
Instance 2Copy codeThe Code is as follows: var element = document. getElementById ('test ');
Var formFieldList = getElementsByTagNames ('input, select, textarea ', element );

Now formFieldList is an array of input, select, and TEXTAREA contained in all the child elements with the ID test, and arranged in the order in which they appear.Copy codeThe Code is as follows: function getElementsByTagNames (list, obj ){
If (! Obj) var obj = document;
Var tagNames = list. split (',');
Var resultArray = new Array ();
For (var I = 0; I <tagNames. length; I ++ ){
Var tags = obj. getElementsByTagName (tagNames [I]);
For (var j = 0; j <tags. length; j ++ ){
ResultArray. push (tags [j]);
}
}
Var testNode = resultArray [0];
If (! TestNode) return [];
If (testNode. sourceIndex ){
ResultArray. sort (function (a, B ){
Return a. sourceIndex-B. sourceIndex;
});
}
Else if (testNode. compareDocumentPosition ){
ResultArray. sort (function (a, B ){
Return 3-(a. compareDocumentPosition (B) & 6 );
});
}
Return resultArray;
}

ExplanationCopy codeThe Code is as follows: function getElementsByTagNames (list, obj)
{
If (! Obj) var obj = document;

First, define the Start Element obj. If not, the default value is document.

Copy codeThe Code is as follows: var tagNames = list. split (',');
Var resultArray = new Array ();

Separate the tag names with commas. Use an array to save the results.

Copy codeThe Code is as follows: for (var I = 0; I <tagNames. length; I ++ ){
Var tags = obj. getElementsByTagName (tagNames [I]);
For (var j = 0; j <tags. length; j ++ ){
ResultArray. push (tags [j]);
}
}

Now we traverse all tag names, use the simplest getElementByTagName () method, and pass the result to resultArray. The main point here is that, because getElementByTagName returns a node list, I cannot use array. concat () to create a new array. One-by-one insertion of elements is the best way I can find.

We get a pointer array for the element of the desired tag Name stored in resultArray, but these elements are still arranged in the order given by the tag. We need to sort the order again.

Copy codeThe Code is as follows: var testNode = resultArray [0];

Now let's start sorting. We need to know whether the browser supports sourceIndex or compareDocumentPosition, and then perform some checks on the raw data we get.

Copy codeThe Code is as follows: if (! TestNode) return [];

If there is no first node (that is, there is no element in the result), an empty array is returned.

Background: array. sort ()
The array. sort () method has an optional function parameter. This function is used to compare two elements (usually called a and B ). If the first one should be in the front, then this function returns a negative number. If the second one should be in the front, a positive value is returned.

SourceIndex
If the browser supports sourceIndex, we will sort the elements by sourceIndex. SourceIndex is a very useful extension of Microsoft. It can be used to know the index value of an element in the source code. The index value of the first element (<HTML>) of the page type is 0, and the second element ( Copy codeThe Code is as follows: if (testNode. sourceIndex ){
ResultArray. sort (function (a, B ){
Return a. sourceIndex-B. sourceIndex;
});
}

We use the value of sourceIndex of the first element to subtract the value of sourceIndex of the second element. If it is a negative value, the first element is in front. If it is a positive value, the second element is in front. This is what sort () needs. Now the elements in resultArray are sorted by their positions in the document.

CompareDocumentPosition
If the browser supports compareDocumentPosition, use this method for sorting. CompareDocumentPosition is the core method of level3. It can compare the positions of two nodes in the document and return a value:

1 not found

2 in front

4 after

8 contain

16 included

For example, if a tag is contained behind another tag, 16 + 4 = 20 is returned.

Copy codeThe Code is as follows: else if (testNode. compareDocumentPosition ){
ResultArray. sort (function (a, B ){
Return 3-(a. compareDocumentPosition (B) & 6 );
});
}

We are only interested in 2 and 4 in the value of compareDocumentPosition: before or after. Therefore, we perform operations on the result and 6, so that the result is 2 or 4 (of course, The result cannot be 6, because an element cannot be after another element before it)

If B is after a, 4 is returned, but sort () requires a negative number. If B is earlier than a, 2 is returned, but sort () requires a positive number. In order to give sort () a correct result, I will subtract 3 from them. In this way, we can get 1 or-1, so that sort () can sort the elements correctly, and the elements in resultArray are also arranged in the order they appear in the document.

Copy codeThe Code is as follows: return resultArray;
}

Then we return resultArray to call its function. Remember, if the browser does not support sourceIndex or the compareDocumentPosition array, no sorting is performed.

Http://www.quirksmode.org/dom/getElementsByTagNames.html
Reprinted please keep the following information
Author: Beiyu (tw: @ rehawk)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.