How js or jquery get parent, child, sibling elements (including ancestors, grandchildren, etc.)

Reprinted from https://lvwenhan.com/web-front/373.html

Native javascript method:

var a = document.getElementById("dom");
      del_space(a); //Clear spaces
      var b = a.childNodes; //Get all child nodes of a;
      var c = a.parentNode; //Get the parent node of a;
      var d = a.nextSibling; //Get the next sibling node of a
      var e = a.previousSibling; //Get the previous sibling node of a
      var f = a.firstChild; //Get the first child node of a
      var g = a.lastChild; //Get the last child node of a

jQuery method:

jQuery.parent(expr) //To find the parent node, you can pass in expr for filtering, such as $("span").parent() or $("span").parent(".class")

jQuery.parents(expr) //similar to jQuery.parents(expr), but finds all ancestor elements, not limited to parent elements

jQuery.children(expr) //Return all child nodes, this method will only return direct child nodes, not all descendant nodes

jQuery.contents() //Returns all content below, including nodes and text. The difference between this method and children() is that, including blank text, will also be returned as a jQuery object, while children() will only return nodes

jQuery.prev() //Return the previous sibling node, not all sibling nodes

jQuery.prevAll() //Return all previous sibling nodes

jQuery.next() //Return the next sibling node, not all sibling nodes

jQuery.nextAll() //Return all subsequent sibling nodes

jQuery.siblings() //Return sibling nodes, regardless of front or back

jQuery.find(expr) //Completely different from jQuery.filter(expr). jQuery.filter() is to filter out a part from the initial jQuery object collection, and the return result of jQuery.find() will not have the content in the initial collection, such as $("p"), find("span") , which starts from the p element, equivalent to $("p span").

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325491370&siteId=291194637