#document.querySselector('.data-include') keeps returning null even tho its right there
27 messages · Page 1 of 1 (latest)
document.querySelector("[data-include]").setAttribute('data-include', 'test')
console.log(document.querySelector("[data-include]"))```
https://codepen.io/chooking/pen/qBgZXgJ?editors=1111
Here is proof that in isolation, the querySelector does work.
I think it's not a good idea to use the same name for a class and a data-attribute
Either there is a problem with using the same class name and attribute name, or you have other code that is modifying the DOM in unexpected ways.
and a shorter way to set data-attributes:
test.dataset.include = 'newTest'```
I noticed that you have two different scripts and one of them has a comment indicating that it loads in the content. Is the HTML that you showed us a modified example or is that really in your actual code? I am wondering if you just showed that to us in the HTML for simplicity but it is actually generated by the JS.
but thats cuz it doesnt have the header.html and index.html and footer.html files loaded in there in that codepen thing or that other script
Loading other code should not cause it to fail unless you have bad code.
its the html that i actually use and the other js (htmlinclude.js) is the one that loads in the content
How are you loading in other HTML files? Are you using some kind of templating language?
no its all just html and js
Does your JS replace the existing element with the contents from another HTML file? If it does, that element can't be selected because it doesn't exist anymore.
also this is the htmlinclude.js file (found it on github its the only onee ive found so far that lets the div data-include='file.html' thing work) https://pastebin.com/NVvX9Lv4
no cuz when i go in the inspecor it still shows div class='data-include'
inspector*
That sets the element's outerHTML. That means it doesn't leave the original element unchanged. Code that sets the innerHTML leave the original element unchanged and only modify its children.
but does it leave the class selector thing unchanged or does it change that
Why are you even using this obscure technique? You could use React or Astro to achieve something similar. These are far more popular and well tested approaches.
tbh it was provided by my instructor
and the class im in doesnt teach react or astro and ive never used those before
I read it again and see that the script code is separate from the outerHTML. It really is modifying elements on the page. It only modifies when an element is in the viewport. You might have seen the elements still existing in dev tools because you were looking at code for elements that had not scrolled into view yet.
but even after scrolling everything into view (almost everything is in view on most pages) it still says null
That's not what I meant. After scrolling, check dev tools to see if those classes still exist. If they don't exist, you should be getting null.