1

Element i have has spaces within the id attribute which is causing the getElementByID() to not work and not be able to capture the element.

If there any workaround i can do in this. Do i have to remove all white spaces in all element ID values i have.

window.addEventListener('DOMContentLoaded', (event) => {
var str=document.getElementById('Monica Finolta Sol ID treReport').id;
alert(str);
})
Salman
  • 1,573
  • 3
  • 13
  • 24
  • 2
    If you have control over your document, you absolutely must get rid of the spaces. https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id – Anurag Srivastava Apr 07 '21 at 08:21
  • See also this answer - https://stackoverflow.com/a/6802804/7867822 – Anurag Srivastava Apr 07 '21 at 08:22
  • But when i inspect element and tried in console document.getElementById('Monica Finolta Sol ID treReport').id; i got below response: "Monica Finolta Sol ID treReport" – Salman Apr 07 '21 at 09:35

1 Answers1

1

Yes! But it is bad practice to have your id contain spaces, as it won't be accessible for a querySelector. Still, it works!

if(document.getElementById('a b')) { 
  console.log("It works!")
}
<p id="a b">Text</p>
Sebastian
  • 1,321
  • 9
  • 21