Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2627

Getting the value of a div tag's special attribute

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

Upvotes: 3

Views: 853

Answers (6)

hamidreza nikoonia
hamidreza nikoonia

Reputation: 2165

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

Upvotes: 1

Rupal
Rupal

Reputation: 1109

You can get it by getAttribute function like

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

You can read about this here

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281894

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

Upvotes: 3

Sudhakar
Sudhakar

Reputation: 324

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

document.getElementsById("container").getAttribute("prjid");

Upvotes: 2

santosh singh
santosh singh

Reputation: 28662

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);

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122006

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>

Upvotes: 6

Related Questions