JS traverses child node search elements and js node search Elements
Function nextChildNode (node, clazz, tagName) {var count = node. childElementCount; for (var I = 0; I <count; I ++) {if (node = undefined | node. children [I] = undefined) {continue;} if (clazz) {if (node. children [I]. getAttribute ('class') = clazz) {return node. children [I] ;}} else {if (node. children [I]. tagName = tagName) {return node. children [I] ;}}return null;} function getChildNode (node, classArg, tagNodeArg) {for (var I = 0; I <classArg. length; I ++) {node = nextChildNode (node, classArg [I]);} for (var I = 0; I <tagNodeArg. length; I ++) {node = nextChildNode (node, null, tagNodeArg [I]);} return node;} function getItemId (node) {var classNode = ['iteminfo ', 'itemdesc'], tagNode = ['P', 'click']; node = getChildNode (node, classNode, tagNode); alert (node. getAttribute ('itemid');} # Call the getItemId function ($ (". shopItem ") [0]);
JS search for parent and child nodes
This writing method is not standardized ~ It is best not to have elements with the same id. An id is only used for one element.
The method to query the parent node is
Var obj = document. getElementById ('A ');
ObjParent = obj. parentNode;
JS problems with searching web page elements
The result obtained by arr is a parent node, which is not an array and cannot be used for loops.
The child element of the parent node -- children
The following functions are slightly modified by you and can only match the first element. If two or more elements have the same attribute and value, the subsequent functions will be ignored.
Function Find (ele, attr, val) {// parent node var parent = ele. parentNode; // child element of the parent node, that is, the same level element of the current element var children = parent. children; // The subelement of the loop for (var I = 0; I <children. length; I ++) {// if this element attribute is equal to a value (val) if (children [I]. getAttribute (attr) === val) {// return this element return children [I] ;}// if no element is found in the loop, return null;} application, test
Window. onload = function () {// reference element, that is, the current element var ref = document. getElementById ("baz"); // Find the element var e1 = Find (ref, "max-length", "64") whose max-length attribute is 64 "); // return the input element console. log (e1); // Find the element var e2 = Find (ref, "class", "bar") whose attribute class is bar; // return the p element console. log (e2); // search for the element var e3 = Find (ref, "title", "link title") whose property title is link title; // return the console of Element. log (e3 );};
<Div id = "foo"> <p class = "bar"> bar <& #4 ...... full text>