How to mention all attributes in single line :)
document.getElementById("image").src = "landscape.jpg";
document.getElementById("image").width = "300";
document.getElementById("image").height = "300";
How to mention all attributes in single line :)
document.getElementById("image").src = "landscape.jpg";
document.getElementById("image").width = "300";
document.getElementById("image").height = "300";
You can't do it in one line, with JavaScript; you can, though, abbreviate to two:
document.getElementById("image").src = "http://lorempixel.com/200/200/nightlife/3";
document.getElementById("image").width = document.getElementById("image").height = "300";
Though, honestly, I'm not sure that you gain anything.
Of course, if you choose efficiency (albeit a micro-optimisation), you go back to three lines again by caching the result of document.getElementById()
:
var image = document.getElementById('image');
image.src = "http://lorempixel.com/200/200/nightlife/3";
image.width = image.height = "300";
It is possible in most, if not all, browsers to use the automagic global variables assigned by the browser, to map a reference to an element with an id
property to a variable of that name (an element with id="image"
is available under a global variable image
):
image.src = "http://lorempixel.com/200/200/nightlife/3";
image.width = image.height = "300";
It is, however, worth noting that while the automagic variables are a possibility, their use is not advisable: global variables, especially in large code-bases or with multiple contributors, are prone to errors and misuse. And, as noted in the comments below, their use is, or may be, deprecated (reference: Do DOM tree elements with ids become global variables?).
All the above was used with the following HTML:
<img src="" id="image" />
You can also save a variable white the element, so you don't have to do document.getElementById each time
var img = document.getElementById("image");
img.src = "landscape.jpg";
img.width = img.height = "300";
you could also make a function the be able to in one line later
function setValues(element, props){
for(var key in props){
element[key] = props[key];
}
}
setValues(document.getElementById("image"), {src: "landscape.jpg", width:"300", height:"300"});
If you need to do a lot of dom manipulation, you could look at a framework like jQuery and zepto, but this becomes overkill, if this is the only thing you need to change.
Use:
with(document.getElementById("image")) { src = "landscape.jpg"; width = "300"; height = "300"; }
Or use jQuery:
$("#image").attr("src", "landscape.jpg").width(300).height(300);
// or
$("#image").attr("src", "landscape.jpg").attr("width": "300").attr("height": "300");
// or
$("#image").attr("src", "landscape.jpg").css({ "width": "300px", "height": "300px" });