dixewi7232
dixewi7232

Reputation: 71

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>

Upvotes: 0

Views: 1531

Answers (3)

Ran Turner
Ran Turner

Reputation: 18126

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

Upvotes: 2

leftclick
leftclick

Reputation: 142

<div id="#myAjax">

in this line you should not use '#'
use

<div id="myAjax">

Upvotes: 0

Anish Roy
Anish Roy

Reputation: 164

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

Upvotes: 1

Related Questions