I have this HTML code multiple times one after the other:
<li>
<img src="path/to/my/picture.jpg" alt="my picture" />
<span>picture title</span>
</li>
and I’m trying to get the path value inside the src attribute of the img tag in a variable, and also the text inside the span in another variable.
I tried this code, but it isn’t working:
clickedLi.onclick = function() {
var imgPath = clickedLi.firstChild;
var pathLi = imgPath.getAttribute("src");
var imgTitle = clickedLi.lastChild;
var titleLi = imgTitle.data;
The clickedLi variable is only a variable that loops through an array containing all the li tags in the document.
So this is the complete JavaScript code I have :
var myLis = document.getElementsByTagName('li');
var liCnt = myLis.length;
for(var i = 0; i < liCnt; i++) {
var currentLi = myLis[i];
currentLi.onclick = function() {
var imgPath = firstElementChild(this);
var pathLi = imgPath.getAttribute("src");
var imgTitle = lastElementChild(this);
var titleLi = imgTitle.firstChild.data;
var myImgDiv = document.getElementById("test");
myImgDiv.innerHTML = '<h2>' + titleLi + '</h2>';
myImgDiv.innerHTML = '<img src="' + pathLi + '" alt="' + titleLi + '">'
}
}
Use
.firstElementChildand.lastElementChildto avoid the whitespace text nodes.You’ll need a shim if you’re supporting older browsers.