-1

I have added an id to all elements with a class of image using JS. The images now have ids eg. image--1, image--2, etc

If I want to get the element by ID using var el = document.getElementById('image--1'); then I get null.

How can I get current DOM in pure JS?

ksav
  • 20,015
  • 6
  • 46
  • 66
Kady
  • 19
  • 1
  • 5
  • Nobody can help you, if you don't provide any code. – elasticman Sep 03 '18 at 09:16
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Sep 03 '18 at 09:21

3 Answers3

1

You can use the setAttribute() method to reliably set the id of image elements, via vanillajs.

Something to also keep in mind here is that the image elements need to be defined and present in the DOM before your javascript executes.

With these two things in mind, consider the following code - you could do something along these lines to achieve what you're after;

<html>
<head>
</head>
<body>

<!-- DEFINE BEFORE SCRIPT -->
<img class="img" src="/yourimage0.jpg" />
<img class="img" src="/yourimage1.jpg" />

<!-- DEFINE SCRIPT AFTER IMAGE ELEMENTS -->    
<script>

    var id = 1;

    // Use the querySelectorAll method to select collection of your
    // image elements
    for(var img of document.querySelectorAll(".img")) {

        // Set the id attribute in this way, using the setAttribute method
        img.setAttribute("id", "image--" + id);
        id++;
    }

    // You can now access the element by id with the following
    var el = document.getElementById('image--1');

</script>

</body>
</html>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

This works. Please explain where your code differs

document.querySelectorAll(".img").forEach(function(img,i) {
  img.id="image--"+i; 
})

document.getElementById('image--1').src = "https://via.placeholder.com/350x150?text=Image1";
  
<img class="img" src="https://via.placeholder.com/350x150" />

<img class="img" src="https://via.placeholder.com/350x150" />

<img class="img" src="https://via.placeholder.com/350x150" />

Dynamically:

// create the images:
var container = document.getElementById("container");
for (var i=0;i<3;i++) {
  var img = document.createElement("img");
  img.src="https://via.placeholder.com/350x150";
  img.classList.add("img");
  container.appendChild(img);
}

document.querySelectorAll(".img").forEach(function(img,i) {
  img.id="image--"+i; // makes more sense to do that in the creation part too
})

document.getElementById('image--1').src = "https://via.placeholder.com/350x150?text=Image1";
<div id="container"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I guess you are using web frameworks like Vue.js or React.js, then this is because of virtual DOM, which means you can't get these elements before they are mounted to real DOM. If so, you should get these element in componentDidMount function.