das kinder
das kinder

Reputation: 1170

select DOM with Jquery

<script type="text/javascript">
  $(function(){
    $('#example')[0].onmouseover = function(event) {
     alert("something");
    };
  });
</script>

<body>
<img id="example" src="example.jpg" " alt="ooooh! ahhhh!"/>
</body

Why do we need [0] behind example id ?

why it's not working if we remove [0] ?

Upvotes: 0

Views: 47

Answers (3)

j08691
j08691

Reputation: 208032

.onmouseover is a JavaScript event handler and only applies to DOM elements. Since $('#example') is a jQuery object, onmouseover wouldn't do anything at all (not even produce an error).

However, each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the underlying element via $('#example')[0] which returns an element that onmouseover (and any other native JavaScript event handler) can work with.

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

Try

$(document).on("mouseover","#example",function(event) {
 alert("something");
};

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

Since you are calling native onmouseover you need to refer native DOM Element

$('#example')[0] // gives native DOM Element.

$('#example')[0].onmouseover=function(){}; //native event handling

If you remove [0] then you are referring jQuery object. So you need to use jQuery way of event handling

$('#example') //gives jQuery object
$('#example').mouseover(function(){}); //jQuery event handling

Upvotes: 3

Related Questions