Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: select an image element inside a div

I have a parent div gal1, inside which there can be further divs and content, but only one img element without an id as you can see below. Now I want to use only Javascript (no jQuery) to change the style of this image, using gal1 as argument (because the rest of the structure inside this div may vary, only this one image will always be there somewhere). I couldn't find any other stackoverflow question that addresses exactly my situation.

<div class="gallery-preview" id="gal1">
    <div class="gallery-preview-img" id="gal-img1">
        <img src="galleries/kevin-carls/Monks.jpg">
    </div>
    <div class="gallery-preview-text" id="gal-text1">
        <span class="gallery-name" href="">Road to India</span><br/>
        <span class="artist-name" href="">Kevin Carls</span>
    </div>
</div>
like image 229
Abhranil Das Avatar asked Jan 16 '12 07:01

Abhranil Das


2 Answers

Than you can make use of method called getElementsByTagName('img') than you should get image and update it.

document.getElementById(gal1).getElementsByTagName('img');
like image 60
Pranay Rana Avatar answered Sep 20 '22 16:09

Pranay Rana


get the content by using id, and then query images by using getElementsByTagName

function getImages(contentId) {
    var content = document.getElementById(contentId);
    // only one image, just return an item; or you can return an array
    if (content) return document.getElementsByTagName('img')[0];
}
like image 30
liunian Avatar answered Sep 21 '22 16:09

liunian