Search code examples
javascripthtmldomqunit

document.getElementById can't find qUnit DOM elements


I'm trying to get a reference to a DOM object created by qUnit, with no luck. It works just fine with a "home made" DOM element. I have made a test site to illustrate the problem. Turn on Firebug or other logging window when visiting the site.

This is the code of the website:

window.onload = function() {

	var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
	console.log("qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);

	var test_element = document.getElementById("test_element");
	console.log("test_element: ", test_element);
};
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Testing 'require' error</title>
</head>
<body>
    <p>See console for output</p>
    <script src="index.js"></script>
    <script src="http://code.jquery.com/jquery-2.2.0.js"></script>
    <p id="test_element">Test element</p>
</body>
</html>


Solution

  • It won't work like this

    I am not talking about qunit but document.getElementById("qunit-testrunner-toolbar"); will return null because there are no element present in this html.

    If you are particularly asking how to get actual id and not null

    You may, add your original script file in this html and then var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar"); will console it in indexjs or if you can include <iframe> in your test html you can do

    <iframe src="urlWithinYourDomain.html" style="display:none" id="iframeId"></iframe> and in indexjs

    var qunitTestrunnerToolbar_element = document.getElementById('iframeId').contentWindow.document.getElementById('qunit-testrunner-toolbar'); if you like html way.