6

I downloaded sizzle.js from https://github.com/jquery/sizzle my code is:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="sizzle.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.onload=load;
        function load(){
            alert(Sizzle("#test"));
            alert(Sizzle("#test").innerHTML);
        }
    </script>
</head>
<body>
<div id="test">abc</div>
</body>
</html>

but alert "[object]", "undefined", please tell me what's wrong with my code?

Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
artwl
  • 3,502
  • 6
  • 38
  • 53

2 Answers2

6

The Sizzle() function returns an array of matched elements. So if you know there'll be exactly one matching element (which there should be if you're selecting by id) try:

alert(Sizzle("#test")[0].innerHTML); 
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • thanks,but why select by id returns an array? in jquery select by id is a single emelemt. – artwl Feb 20 '12 at 03:39
  • 7
    No, in jQuery `$("#test")` returns an array too (well, an array-like object). It's just that in jQuery when you use jQuery methods on the result like `$("#test").html()` the jQuery methods know they're dealing with an array, they don't give an error if nothing matched, and for methods that return a value (like `.html()`) if more than one element matched they just return the value from the first one. – nnnnnn Feb 20 '12 at 03:42
0

You've did a slight mistake it returns NodeList not a single Node. The NodeList is like an array but used for storing Nodes. You may probably want to use the first one.

// this is how you do it
alert( Sizzle('#test')[0].innerHTML );