如何通过id获取span元素?

Actually i create a popup with close icon and i try to close popup form using span method. I want to get span element value by element id.

       <script>
  // Get the modal
  var modal = document.getElementById('myModal');

  // Get the button that opens the modal
  var btn = document.getElementById("myBtn");

  // Get the <span> element that closes the modal
  var span = document.getElementsByClassName("close")[1];

  // When the user clicks the button, open the modal
  btn.onclick = function() {
    modal.style.display = "block";
  }

  // When the user clicks on <span> (x), close the modal
  span.onclick = function() {
    modal.style.display = "none";
  }

  // When the user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  }
  </script>

You can try to use getElementByTagName or getElementById instead of by the class.

Alternatively, try to add the attribute onclick directly in the DOM on the wanted span element, and then call a function which does what you want.

Hope it helped.

I'm not sure where the .onclick is coming from but add events in js that are not inline in an html element is different. For instance you wouldn't say

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

you would say

btn.addEventListener('click', function() {
    modal.style.display = 'block';
});

if you were using jQuery you could do something like

$('#myBtn').click(function() {
    modal.style.display = 'block';
});

or

$('#myBtn').on('click', function() {
    modal.style.display = 'block';
});

but that just comes down to preference as you can also add the event to the document and specify the target

$(document).on('click', '#myBtn', function() {
    modal.style.display = 'block';
});