简体   繁体   中英

document.querySelector is null

I have an error to resolve at document.querySelector('#myAjax') : TypeError: document.querySelector(...) is null

Below my code. what's the problem? thank you

<div id="#myAjax"></div>

<script>
  window.addEventListener("DOMContentLoaded", (event) => {
    console.log("DOM uploaded and analysed");
    document.querySelector('#myAjax')
      .addEventListener('click', function(e) {
        let selectedOptionVal = document.querySelector('#move_to_category_id').value,
          options_html = "";
        fetch("{$categories_ajax}?" + selectedOptionVal)
          .then(function(response) {
            return response.json();
          })
          .then(function(jsonResponse) {
            // Ajax success
            console.log("data is :", jsonResponse);
            for (const index in jsonResponse) {
              let category_id = jsonResponse[index].id;
              let category_name = jsonResponse[index].text;
              let selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
              options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
            }
            $('#move_to_category_id').html(options_html);
          })
          .catch(function(err) {
            // error ajax 
            alert("error :" + err);
          });
      });
  });
</script>

The CSS id selector uses the ID attribute of an HTML element to select one unique element on a page. To use an ID selector in CSS, you write a hashtag # followed by the ID of the element but there is no need and actually very confusing and wrong to add the # in the value of the attribute.

Bottom line, you need to remove the # from the id attribute. change it from:

<div id="#myAjax"> // wrong

To

 <div id="myAjax"> // correct

Remove # from the component div id: <div id="myAjax"></div>

<div id="#myAjax">

in this line you should not use '#'
use

<div id="myAjax">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM