How to set the attribute of a child element within another element using javascript
pure? Home
in jquery
would be: $('.preview').find('img').attr('src','#url');
but how does it stay in javascript
pure?
<div class="preview"><img src="" title=""/></div>
var el = document.getElementsByClassName("preview");
var img = el.getElementsByTagName('img');
img.setAttribute("src" , 'url');
I tried with your answer but it did not work: in the console it appears: 'undefined'
var reader = new FileReader();
reader.onload = function (e){
document.getElementsByClassName("preview")[0].querySelectorAll("img")[0].setAttribute("src", e.target.result);
};
reader.readAsDataURL(files[0]);
This function is called in the change
event of the input file
What I'm trying to do is get the url of the image that is loaded into the input and it shows a thumbnail, the code works at jquery
but I need to do at javascript
this works:
<img src="" alt="" id="preview">
document.getElementById("preview").setAttribute('src', 'url');