Grasshopper
Grasshopper

Reputation: 1808

how to get XML object from HTML document in JQUERY

I have to retrieve hier2 object in jquery from following HTML code in ASPX page

<div>
<hier2:hierarchy >
 <hier:x1></hier:x1>
<hier2:hierarchy >
</div>

I trier document.all.hier2 in IE 11 and its not working

what is the best approach to do this.

Upvotes: 0

Views: 264

Answers (1)

Mouser
Mouser

Reputation: 13304

simply put:

document.getElementsByTagName("hier2:hierarchy"); 

returns a node list you can loop over containing all the hier2:hierarchy nodes.


More elaborate:

Those elements (or nodes) are part of the Document Object Model (DOM). In the past IE (and others) supported document.all. It's now deprecated. How to traverse the DOM. The DOM is a tree that contains a root and its children, grandchildren, etc.

basics:

  • document: This is the master object. The root of the page. All other elements are a descendant of this root.
  • document.documentElement: representing the HTML-element of the page.

Traversal:

  • document.getElementById: allows you to select a single element based upon its ID-attribute.
  • document.getElementsByTagName: allows you to select multiple nodes based upon the node name.
  • document.getElementsByClassName: allows you to select multiple nodes based upon the node's class.
  • document.querySelector: select a single node using css-selectors
  • document.querySelectorAll: same as the above, only for selecting multiple elements.
  • children or childNodes: a subtle difference, the first selects content nodes, while the latter selects all the nodes that are direct children (in the form of a node list) of an element.
  • parentNode or parentElement: select the parent element of the current element.
  • previousSibling or nextSibling: select the previous or next element.

Many more options here: https://developer.mozilla.org/en-US/docs/Web/API/Element

Some examples:

plain:

var elements = document.getElementsByTagName("hier2:hierarchy");
for (var i = 0; i < elements.length; i++)
  {
    document.querySelector("#display").innerHTML += elements[i].nodeName; //select the display div using css selector #display
  }
<div>
  <hier2:hierarchy>
    <hier:x1></hier:x1>
  </hier2:hierarchy>
</div>
<div id="display"></div>

In jQuery

  $("hier2\\:hierarchy").each(function() {

    $("#display").html(this.nodeName);
  });


//$("hier2\\:hierarchy") is used to select the elements, mind the \\ to escape!
//each is used to traverse all the elements.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <hier2:hierarchy>
    <hier:x1></hier:x1>
  </hier2:hierarchy>
</div>
<div id="display"></div>

Special reminder here: In using hier2:hierarchy will fail. You need to escape the : with \\: to

$("hier2\\:hierarchy")

Upvotes: 1

Related Questions