Skip to content Skip to sidebar Skip to footer

Getting The Value Of A Div Tag's Special Attribute

If next command: console.log(document.getElementById('container')); prints:
...
why the next command: console.log(document.

Solution 1:

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"));
<divid="container"prjid="ABCDE">...</div>

Solution 2:

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'));
<divid="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

Solution 3:

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

Solution 4:

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

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

Solution 5:

You can get it by getAttribute function like

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

You can read about this here

Post a Comment for "Getting The Value Of A Div Tag's Special Attribute"