Home > other >  getElementbyId does not work and returns null
getElementbyId does not work and returns null

Time:05-16

When accessing the site, the image and characters are displayed for a moment with JavaScript, It takes a lot of time to load the image, and we have to lengthen the fade-out time.

Once you visit the site, the cache will remain, so when you visit it again, the image will be displayed immediately and you will feel that 3 seconds is longer.

Therefore, I am trying to set it so that it can fade out after the image has been read.

When I run the test code below, document.getElementById('firstimgs'); is null and no log is output. When I changed it to querySelectorAll("img");, the code worked, but I can't do what I want to do this time because all the images are targeted.

Do you know what caused it?

<div >
    <p><img src="<?php echo esc_url(get_template_directory_uri()); ?>/imgs/top/first-banner.jpg" alt="r" id="firstimgs"></p>
    <span>text</span>
</div>
 function firstimg(){

  $('.first-img p').fadeIn(500);
      $('.first-img span').fadeIn(500);
    };
    setTimeout(firstimg, 10);
    window.addEventListener('DOMContentLoaded', function(){
        var img_elements = document.getElementById('firstimgs');
        for (var i = 0; i < img_elements.length; i  ) {
            img_elements[i].addEventListener('load', (e) => {
                console.log(" load");
            });
            img_elements[i].src = img_elements[i].getAttribute("src");
        }
      });

CodePudding user response:

document.getElementById()

return single element

document.getElementById

function firstimg() {
  $('.first-img p').fadeIn(500);
  $('.first-img span').fadeIn(500);
};

setTimeout(firstimg, 10);

window.addEventListener('DOMContentLoaded', function() {
  var img_elements = document.getElementById('firstimgs');
  img_elements.addEventListener('load', (e) => {
    console.log(" load");
  });

  img_elements.src = img_elements.getAttribute("src");
});

CodePudding user response:

  1. Missing error: I found that the id in your document.getElementById('firstimg') is not the same as the id of the element. It is missing the 's' character.

  2. Suggestion: If you are looking to get an array then use class instead of id, and to get elements by class use getElementsByClassName('firstimgs') instead getElementById('firstimg'). Because id is used for an element if it is the same, get the first element.

  • Related