Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery is not finding elements

jQuery is not finding any elements. alert($("#testbutton").length); displays 0 every time.

Am I doing something wrong?

My JS / jQuery code:

(function ($) {
    alert($("#testbutton").length);
}) (jQuery);

My HTML:

<html>
    <body>
        <div id="header">
            <div class="button" id="testbutton">Test</div>
        </div>
    </body>    
</html>
like image 640
Mihail Burduja Avatar asked Jan 16 '23 15:01

Mihail Burduja


1 Answers

When your code runs the DOM is not ready so the element doesn't exist. Did you mean to do this instead (passing a function to jQuery is a shortcut for $(document).ready(fn)):

$(function () {
    alert($("#testbutton").length);
});
like image 109
James Allardice Avatar answered Jan 25 '23 20:01

James Allardice