Reputation: 13
I'm trying to alter the source attribute of an image element in HTML through JS. But my issue is that I am unable to edit any attributes of the element.
If I try to log the attribute to the console, it returns undefined. But if I log .innerHTML, it will show me it's content just fine. .setAttribute won't do anything either. How do I amend such that I am able to edit the attributes of the image element?
HTML
<!DOCTYPE html>
<html>
<head>
<title>Ringve musikkhistoriske museum</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/CSS/stilark.css">
</head>
<body>
<div class="overskrift">
<h1 class="overskrift">Ringve musikkhistoriske museum</h1>
</div>
<ul>
<li>Arrangementer</li>
<li>Test din kunnskap</li>
</ul>
<div id="innpakking">
<div id="infoKnapper">
<img height="80" width ="85" src="/V2018-Museum-filer/informasjon.jpg" alt="Kunne ikke laste bilde">
<img height="80" width ="85" src="/V2018-Museum-filer/aapningstider.jpg" alt="Kunne ikke laste bilde">
<img height="80" width ="85" src="/V2018-Museum-filer/priser.jpg" alt="Kunne ikke laste bilde">
</div>
<div id="bildeGalleri">
<img height="700" width ="980" src="/V2018-Museum-filer/intro1.jpg" alt="Kunne ikke laste bilde">
</div>
<div id="bildeKnapp">
<button>Neste bilde</button>
</div>
</div>
</body>
<script src="/JS/kode.js"></script>
</html>
Javascript
var bilderEL = document.querySelector("#bildeGalleri");
var bildeKnappEL = document.querySelector("#bildeKnapp");
var bildeTeller = 1;
console.log(bilderEL["src"]);
console.log(bilderEL.src);
console.log(bilderEL.innerHTML);
Upvotes: 0
Views: 330
Reputation: 56720
Several mistakes:
div
, not the img
.div
doesn't have a src
property.document.querySelector("#bildeGalleri img")
.<script>
as a child of <html>
.</body>
.img
tag doesn't have innerHTML
because it's a void element. The parent element <div>
has.bilderEl.parentElement.innerHMTL
.Upvotes: 1
Reputation: 2197
In your javascript, you aren't selecting the image itself, you're selecting the div that contains it. Change your selector to something like this:
var bilderEL = document.querySelector("#bildeGalleri img");
Upvotes: 0
Reputation: 435
First you need to remove the id from the parent and to put the id on the img element itself:
<img height="700" width ="980" src="/V2018-Museum-filer/intro1.jpg" alt="Kunne ikke laste bilde" id="bildeGalleri">
Then you want to select it by id in JS to be like that:
var bilderEL = document.getElementById("bildeGalleri");
console.log(bilderEL.src);
Upvotes: 0