Here is the HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.js"></script>
<script type="text/javascript" src="access.js"></script>
</head>
<body>
<button id="trigger"></button>
<img id= "testElement" style= "position: absolute; border-color: white; top:340px; left:615px;" width="34px" height= "34px" />
</body>
</html>
And the access.js file is:
$(document).ready( function(){
$('#trigger').click(function(){
$('#testElement').src="success.png";
//THIS WON'T WORK.
document.getElementById('testElement').src= "success.png";
//BUT THIS WORKS.
});
});
I know that if I use $, the return object is a jQuery object. It's not the same as getElementById. But why the jQuery selector can't work here?
I need the jQuery object to make more operations like "append/style"...
Thanks.
UPDATE Too many correct answers appeared at almost the same time... Please give more explanation to let me decide who I should give the credit, thanks!
Sorry for my poor understanding of your correct answers... I just want more details.
Are all the attribute nodes (src/width/height...) not the property of jQuery object? So does the jQuery selector only select DOM Element Node like img/p/li/div node ? (<> causes some error.)
PLEASE TAKE A LOOK AT THE UPDATED INFORMATION... Thank you!
A jQuery element is a DOM element wrapped in an array-like jQuery object so you have access to all the jQuery methods, but that means you "lose" access to the original DOM methods and properties. You can either use a jQuery method or grab the original DOM element to be able to use the vanilla properties.
$('#testElement').attr('src', 'success.png');
$('#testElement')[0].src = 'success.png';
--^-- get DOM element
Because you need to use the .attr()
jQuery method on the jQuery object:
$('#testElement').attr("src", "success.png");
Should be
$('#testElement').prop("src","success.png"); //1.6 and above
OR
$('#testElement').attr("src","success.png"); //before 1.6
The way you access property in JavaScript and JQuery is different
document.getElementById('testElement').src= "success.png";
can also be achieved with
$('#testElement')[0].src = "success.png";
src
is not a property of a jQuery object. You need to do
$('#testElement').attr('src', 'success.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With