0

I have the following divs:

 <div  id='1'   title='A'  description='B' activity-note='C'  grouped-as='Test'>  </div>
 <div  id='4'   title='Z'  description='Z' activity-note='Z'  grouped-as='Soil Prep'>  </div>
 <div  id='5'   title='Q'  description='Q' activity-note='Q'  grouped-as='Soil Prep'>  </div>

I would like to get the values for each of the assigned items in the div.

I have tried using the following (as an example) but I get an error:

title=document.getElementById('1').getAttribute("title");

Obviously I am confused and so any help and/or guidance would be appreciated.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
Jack Stein
  • 123
  • 1
  • 14
  • That line should work. What's the problem? – technophyle Jul 19 '23 at 01:28
  • What's the error you get? – Ouroborus Jul 19 '23 at 01:32
  • get the following in Chrome: Uncaught TypeError: Cannot read properties of null (reading 'getAttribute') – Jack Stein Jul 19 '23 at 01:42
  • 1
    Can you edit this question and post how your JS relates to your HTML (as in, is it placed in the head element? Elsewhere?). I have a suspicion it's a race condition issue. JS is fast and will attempt to access elements before the DOM is actually rendered. – Major Productions Jul 19 '23 at 01:47
  • @JackStein Seems to work OK in Chrome. https://codepen.io/ceejayoz/pen/dyQejoB – ceejayoz Jul 19 '23 at 01:47
  • Where is your JS in relation to your elements? This may be a load order issue. https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – disinfor Jul 19 '23 at 03:59
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – disinfor Jul 19 '23 at 04:00
  • The issue was due to how I was generating the
    I generated each div in the php code after each
    – Jack Stein Jul 19 '23 at 11:21

1 Answers1

0

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

Similarly, an id starting with a digit (E.g., 1234-322-678) or a hyphen followed by a digit (E.g., -123), though valid in HTML, may lead to problems when used in CSS, JavaScript, and Web APIs:

Such an id is not a valid JavaScript identifier. Elements with IDs become global properties, but you cannot use non-identifier global properties as global variables — 1234 is not a global variable, and you have to use window[1234] instead to get the element with id="1234". This is slightly inconvenient as you have to create the variable with an extra step: const element = window[1234].

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • I changed the id to not be numeric -
    still get the following in Chrome: Uncaught TypeError: Cannot read properties of null (reading 'getAttribute')
    – Jack Stein Jul 19 '23 at 01:39