问题
My JavaScript module fails to find a particular DOM element with a classname using $('.classname')
even when the element exists.
$('.classname').length
returns 0, where as $.find('.classname').length
returns 1.
Website contains other JavaScript modules also.
Can anyone help me to find why this is happening?
My jQuery version is 1.7.1.
To reproduce this
1- Go to avc.com
2- Open console.
3- Paste the following code in console.
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
script.async = true;
head.appendChild(script);
4- Try$('.pkg').length
and $.find('.pkg').length
.
Find the screen-shot from here http://i.imgur.com/4UDHz.png
One more point, if you try this in some other websites, It works correctly.
回答1:
You may have some conflicts with your other JavaScript modules. Look into jQuery noconflict
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict()
Try using
jQuery('.classname').length
来源:https://stackoverflow.com/questions/9890878/jquery-classname-length-fails-but-find-classname-length-works-why