So I'm trying to grab some attributes of a div table from the DOM from within a script - and failing.
Code should speak for itself:
<head>
<script type = "text/javascript" src = "SCRIPT_IN_QUESTION.js"></script>
</head>
<body>
<div id = "my_elements">
<!-- I want to access 'attribute-one' data attributes from
all children -->
<div data-attribute-one = "Hello"></div>
<div data-attribute-one = "World"></div>
</div>
</body>
I've seen how this is done with an embedded script in the DOM using something along the lines of:
<script type = "text/javascript">
var values = document.getElementById('my_elements').childNodes;
var foo = values[0].getAttribute('data-attribute-one');
</script>
I'm trying to access these attributes from within a script that isn't embedded into the DOM, and getAttribute is undefined - guess you can only ue that within the DOM.
How do I access this data in a script 'outside' the DOM?
As the below comment states, doing this after the DOM has been loaded makes sense to do, and I'm doing it something like:
window.addEventListener('load', onload, false);
function onload(){
var data = document.getElementById('canvas_segments').childNodes;
//This throws an undefined error
var attribute = data[0].getAttribute('data-attribute-one');
}
Many thanks