1
How to define the attribute of a child element within another element using javascript
pure?
in jquery
would be: $('.preview').find('img').attr('src','#url');
but how does it get 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: on the console 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 event change
of input file
what I am trying to do is take the image url that is loaded into the input and shows a thumbnail, the code works in jquery
but I need to do in javascript
that way it works:
<img src="" alt="" id="preview">
document.getElementById("preview").setAttribute('src', 'url');
document.getElementById("preview")
this wrong,document.getElementById
is for Ids and not CLASS, and something elsedocument.getElementById
returns only one element ornull
, other thangetElementsByClassName
andgetElementsByTagName
returning multiple, eternal elements.– Guilherme Nascimento
I know I was testing and I ended up bringing it wrong here, anyway it doesn’t work when I change to
class
– Hebert Lima
Be careful when using the id property, you should not reference two elements with the same id
– MarceloBoni
I know, so I need to use with
getElementsByClassName
;)– Hebert Lima