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
答案 0 :(得分:4)
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>
答案 1 :(得分: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
答案 2 :(得分: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);
答案 3 :(得分:2)
Instead of doing this you can get data attribute to that like below
document.getElementsById("container").getAttribute("prjid");
答案 4 :(得分:1)
You can get it by getAttribute
function like
console.log(document.getElementById('container').getAttribute("prjid"));
You can read about this here
答案 5 :(得分: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