Simple question really, I'm using the getElementById to target my div standby and change its styling. Now, I can't for the love of anything find out how to target what is written in my CSS as #standby img, that is, the img tag within standby. How would I target this and change its styling with JavaScript?
-
how do you know it's a simple question ;-)Christophe– Christophe2013-03-12 22:19:07 +00:00Commented Mar 12, 2013 at 22:19
-
2document.querySelector('#standby img') is fine? ;-) caniuse.com/#feat=queryselectormariozski– mariozski2013-03-12 22:19:10 +00:00Commented Mar 12, 2013 at 22:19
-
mariozski That's exactly what I needed!NollProcent– NollProcent2013-03-12 22:52:55 +00:00Commented Mar 12, 2013 at 22:52
4 Answers
For plain javascript in all browsers, it would be this:
var imgs = document.getElementById("standby").getElementsByTagName("img");
In more advanced browsers, you could use this:
var imgs = document.querySelectorAll("#standby img");
Each of these returns a nodeList (which is like an array of DOM elements) that you can then iterate over.
You could then iterate the results of either of these like this:
for (var i = 0; i < imgs.length; i++) {
imgs[i].style.width = "300px";
}
If you know there is one and only one image in that div, then you could just do this rather than iterating over more than one:
document.getElementById("standby").getElementsByTagName("img")[0].style.width = "300px";
1 Comment
You can do this easily with jQuery. $('#standby img'). Worth looking into.
4 Comments
So you've already got the standby element using getElementById().
To get the img elements within it, you need to use getElementsByTagName()
var standby = document.getElementById('standby');
var standbyImgs = standby.getElementsByTagName('img');
I guess you already have the first line, so you just need the second. Or combine them into one.
Important to note that getElementsByTagName() returns an array of elements, not a single element like getElementById(). Because obviously, there could be more than one img there, whereas there should only ever be one element with a given ID.