Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector strangeness -- is this a bug or am I doing it wrong?

Tags:

jquery

I'm getting inconsistent results across browsers with the following test:

============ test.html ===========

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<body>
<script>

var xml;



$.ajax({
  type: "GET",
  url: "data.xml",
  success: function(data){
      var node = $("CI:first", data);
      var query1 = $("T TX", node).length;
      var query2 = $("T", node).find("TX").length;


      var msg = '$("T TX", node).length: ' + query1;
      msg += "\n";
      msg += '$("T", node).find("TX").length: ' + query2;
      alert(msg);
  }
});


</script>
</body>
</html>

============ data.xml ===========

<?xml version="1.0" encoding="ISO-8859-2"?>
 <CNs>
   <CI>
     <T>
       <TX></TX>
     </T>
   </CI>
   <CI>
     <T>
       <TX></TX>
     </T>
   </CI>
   <CI>
     <T>
       <TX></TX>
     </T>
   </CI>
 </CNs>

What should happen is this:

  • Load xml via ajax call
  • select an xml node: $("CI:first", data);
  • select a node within that node: $("T TX", node)
  • second selection should only come up with one "TX" tag

However, in IE6 and IE8 (haven't tried IE7), the second selection seems to ignore the "node" context, and search the entire xml document. The test runs as expected in FireFox and Safari. Doing it this way works in IE $("T", node).find("TX"). Any explanations of why $("T TX", node) doesn't work in IE?

like image 389
morgancodes Avatar asked Jun 11 '09 13:06

morgancodes


2 Answers

My guess is a bug in the JQuery code for :first. I remember a while ago seeing a thing about getting IE to allow the first-child CSS pseudo class to work you need to have a DOCTYPE. No doctype on the XML...so maybe that's it.

I would just switch from $("CI:first") to $("CI").eq(0). $("CI") will give an array of all the CI elements, and eq(0) will give you the first element.

like image 195
Ben Avatar answered Nov 15 '22 03:11

Ben


It's a bug.

Filed at dev.jquery.com/ticket/4748, at the request of John Resig.

like image 27
morgancodes Avatar answered Nov 15 '22 04:11

morgancodes