title: Getting element using xpath and cheerio
body: <p>Trying to write a function in node.js that will get the element by xpath.</p>
  
  <p>I have an xpath of the desired dom element like </p>
  
  <pre><code>xpath = '/html/body/div/div[2]/div/h1/span'
  </code></pre>
  
  <p>My DOM is loaded in <strong>cheerio</strong> via fs module (because I have this webpage stored locally):</p>
  
  <pre><code>var file = fs.readFileSync( "aaa.html" )
  var inDom    = cheerio.load( file )
  </code></pre>
  
  <p>Then I am trying to iterate via each xpath part, get the element of the dom tree, check it's children if the name and element number matches, and if they do, store <strong>rez</strong> as this mathed element. Then I do continue to dig down with new xpath part. The code looks like this, but it fails to get what I want because just after I get the first mach and set <strong>rez</strong> as the matched element, in the next for loop cycle this new element seems not to have any children elements.</p>
  
  <pre><code>var rez = inDom('html');
  var xpath = inXpath.split( "/" );
  for( var i = iterateStart; i &lt; xpath.length; i++ ) {
      var selector = xpath[ i ].split('[')[0];
      var matches = xpath[ i ].match(/\[(.*?)\]/);
      var child = 0;
      if( matches ) {
          child = matches[ 1 ];
      }
  
      for( var k = 0; k &lt; rez.length; k++ ) {
          var found = false
          var curE = rez[ k ]
  
          for( var p = 0; p &lt; curE.children.length; p++ ) {
              var curE_child = curE.children[ p ]
  
              if( curE_child.name = selector ) {
                  if( child &gt; 0 ) {
                      child--
                  }
                  else {
                      rez = curE_child
                      found = true
                      break
                  }
              }               
          }
          if( found ) {
              break
          }
      }       
  }
  </code></pre>
  
  <p>Can anybody help me with the code using mentioned node.js modules?</p>