3

If next command:

 console.log(document.getElementById('container'));

prints:

 <div id="container" prjid="ABCDE">...</div>

why the next command:

 console.log(document.getElementById('container').prjid);

prints undefined? I am trying to get the value of prjid

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Jose Cabrera Zuniga
  • 2,348
  • 3
  • 31
  • 56

6 Answers6

5

prjid is an attribute. You should use the function getAttribute to get any attributes value.

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string);


 console.log(document.getElementById('container').getAttribute("prjid"));
 <div id="container" prjid="ABCDE">...</div>
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

In order to get prjid which isn't a defined attribute on div rather a custom one, you would use getAttribute

document.getElementById('container').getAttribute('prjid')

Snippet

console.log(document.getElementById('container').getAttribute('prjid'));
<div id="container" prjid="abd"/>

According the MDN docs:

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string);

Note: In React you shouldn't use document.getElementById and rather use refs. Check this answer

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
2

In order to get prjid use getAttribute

document.getElementById('container').getAttribute('prjid');

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string);

santosh singh
  • 27,666
  • 26
  • 83
  • 129
2

Instead of doing this you can get data attribute to that like below

document.getElementsById("container").getAttribute("prjid");
Sudhakar
  • 324
  • 3
  • 9
1

You can get it by getAttribute function like

console.log(document.getElementById('container').getAttribute("prjid"));

You can read about this here

Rupal
  • 1,111
  • 6
  • 16
1

if you want get an value , and that value place in an custom attribute you must use getAttribute() method , some thing like this

var pjid = document.getElementById('container').getAttribute('pjid');

and create this attribute in your element

<div id="container" pjid="some-thing" >

but i thing you are this problem in React , because you Tag reactjs , in react ( prev version - less than 16 ) , JSX delete all undefined attribute but this problem solve in react 16 , you must migrate to this version

hamidreza nikoonia
  • 2,007
  • 20
  • 28