how to use sizzle.js separate
Asked Answered
D

2

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?

Deneendenegation answered 20/2, 2012 at 3:11 Comment(0)
F
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); 
Fernand answered 20/2, 2012 at 3:36 Comment(2)
thanks,but why select by id returns an array? in jquery select by id is a single emelemt.Deneendenegation
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.Fernand
P
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 );
Peavey answered 26/1, 2019 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.