javascripthtmldom

Getting DOM element information from javascript


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


Solution

  • Use .children instead of .childNodes (which also includes text nodes). And you may need to wrap your call into onload event, e.g.

    <body onload="onLoad()";>
          <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>
    

    and in your script:

    function onLoad() {
       var values  = document.getElementById('my_elements').children;
       var foo = values[0].getAttribute('data-attribute-one');
    }