Reputation: 2315
This is my html code
<div class="class_test" id="id_test">
<h2>testing</h2>
<img/>
<div class="rightBox">
<h4>test</h4>
<p>test</p>
</div>
</div>
in javascript code, i want to select img to set it's src , height , width
$("#id_test > img").src = "blablabla.jpg";
$("#id_test > img").height = "100";
$("#id_test > img").width = "100";
but it doesn't work
Where did i miss it ?
Otherwise, how do i use the native javascript code without using jquery
document.getElementById("blabla")
i don't want to set the img ID
Upvotes: 0
Views: 216
Reputation: 4144
jQuery returns array like object .. eg : $("#id_test > img")
returns the following array
[<img/>,<img />, ...]
For accessing it you can loop them using for
, while
.. or jQuery each
method .
$("#id_test > img")[0] -> is Dom
Changing it will reflects into Dom .. But you should care your selector
passing . If selector is not valid one .. jQuery Object.length
is 0
see difference between property and attribute on question Properties and Attributes in HTML
var imgs = $("#id_test > img");
// set first item ..
if ( imgs.length > 0 ) {
imgs[0].src = 'your src';
}
// set all items
if ( imgs.length > 0 ) {
for ( var i= 0; i < imgs.length ; i++ ){
imgs[i].src = 'your src'; // src is property
}
}
The best way is to use jQuery prop method . Which set src
property for all items , same like above for loop
code .jQuery is safe for working on different browsers
imgs.prop('src','your src') // or pass json params
In hehind loop each item ,... and set properties
Upvotes: 0
Reputation: 28837
Width jQuery:
$("#id_test > img").prop('src','http://jsfiddle.net/favicon.png');
$("#id_test > img").prop('height','100');
$("#id_test > img").prop('width','100');
Width javascript
var elm = document.getElementById('id_test');
var first = elm.getElementsByTagName("img")[0];
first.src = "http://jsfiddle.net/favicon.png";
first.style.height = '100px';
first.style.width = '100px';
Upvotes: 1
Reputation:
I think that should work:
$('#id_test').find('img').attr({ 'src': 'blablabla.jpg', 'height': 100, 'width': 100});
Upvotes: 1
Reputation: 2469
Try:
$("#id_test > img").attr('src',"blablabla.jpg").attr('height',"100").attr('width',"100");
Upvotes: 1