Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  16] [ 6]  / answers: 1 / hits: 22440  / 13 Years ago, thu, november 24, 2011, 12:00:00

Example:



<div class=test><img src=test.jpg style=display:none; /></div>


How to change that with javascript, I know in css its:



.test img {display:block;}


but in javascript I only know this:



document.getElementById(test).style.display=block;


thats obviously the whole div tag , not the img.


More From » javascript

 Answers
25

If you're using an ID test, you can do this.



document.getElementById(test)
.getElementsByTagName(img)[0].style.display=block;


This uses getElementsByTagName which returns a collection of the images found. The [0] grabs the image at index 0 (the first image), and then applies the style.



If you have a class test, you can do this, but it won't work in IE7 and below:



var imgs = document.querySelectorAll(.test > img);

for( var i = 0; i < imgs.length; i++ ) {
imgs[i].style.display=block;
}


For the widest browser compatibility, you can do this:



function getElementsByClassName( root, clss ) {
var elems = document.getElementsByTagName('*'),
result;
clss = + clss + ;
for( var i = 0; i < elems.length; i++ ) {
if( ( + elems[ i ].className + ).indexOf( clss ) > -1 ) {
result.push( elems[i] );
}
}
return result;
}

var tests = getElementsByClassName( document, test );

for( var i = 0; i < tests.length; i++ ) {
var img = tests[i].getElementsByTagName('img')[0];
if( img ) {
img.style.display=block;
}
}

[#88917] Wednesday, November 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopherw

Total Points: 173
Total Questions: 107
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;