javascript - Why when trying to use JQuery on a previously initialized html element variable it returns undefined? -
i read on jquery docs ( https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-elements-when-i-already-have-a-dom-element/ ) use initialized element writing variable name selectors:
$(element)
but whenever try function call @ press of button returns 'undefined'.
this example code did test out in more controlled environment:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container-fluid"> <div class="row"> <div class="col-md-6"> <button class="btn btn-block btn-primary" onclick="jquery(this)">jquery</button> </div> <div class="col-md-6"> <button class="btn btn-block btn-info" onclick="normaljs(this)">normaljs</button> </div> </div> <div class="row"> <div class="col-md-6"> <button class="btn btn-block btn-danger" onclick="basictest()">basictest</button> </div> <div class="col-md-6"> <button class="btn btn-block btn-info" id="empty">dynamictest</button> </div> </div> </div> <script> function jquery(caller){ var element = $(caller).parent(); alert("tag name: " + element.tagname); } function normaljs(caller){ var element = caller.parentelement; alert("tag name: "+ element.tagname); } function basictest(){ alert("this basic test"); } $("#empty").click(function(){ alert("tag name: " + $(this).tagname); alert("tag name: " + this.tagname); }); </script>
am doing wrong?
by $(caller)
, "converted" dom element jquery object, therefore, dom properties , methods won't work in normal way on anymore, if want tagname using jquery, prop()
:
function jquery(caller){ var element = $(caller).parent(); alert("tag name: " + element.prop("tagname")); }
Comments
Post a Comment