Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery selector can't work but getElementById works in this scenario?

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!

like image 222
Alston Avatar asked Nov 25 '12 04:11

Alston


4 Answers

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
like image 150
elclanrs Avatar answered Sep 28 '22 05:09

elclanrs


Because you need to use the .attr() jQuery method on the jQuery object:

$('#testElement').attr("src", "success.png");
like image 31
armen.shimoon Avatar answered Sep 28 '22 05:09

armen.shimoon


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";
  • .attr()
  • .prop()
like image 30
codingbiz Avatar answered Sep 28 '22 05:09

codingbiz


src is not a property of a jQuery object. You need to do

$('#testElement').attr('src', 'success.png')
like image 28
bhamlin Avatar answered Sep 28 '22 06:09

bhamlin