pavlos pavlos - 27 days ago 11
jQuery Question

Jquery could not select elem by id

<input type="button" id="elem" value="Search">

<script>
var elem1 = $("#elem");
elem1.onclick = hello;

function hello() {
alert("hello");
}
</script>


I don't understand why couldn't I select id element by Jquery, how I could do with JS document.getElementById

Answer

As elem1 is a jQuery object, It doesn't have onclick property. You can use either of these method to bind the event handler.

Here, [0] will get the underlying DOM element then you can use onclick

elem1[0].onclick = hello;

or use .on() to bind the event handler

elem1.on('click', hello);
Comments