Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual studio 2015 javascript access to dom elements

In a Visual Studio 2015 "Javascript universal Windows" application I have this very simple code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <!-- WinJS references -->
    <link href="WinJS/css/ui-dark.css" rel="stylesheet" />
    <script src="WinJS/js/base.js"></script>
    <script src="WinJS/js/ui.js"></script>

    <!-- aaaaa references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>

<body class="win-type-body">

    <div id="myDiv">BEFORE</div>

    <script>            

        window.onload = function () {
            document.getElementById("myDiv").innerHTML = "AFTER";
        };


    </script>
</body>

</html>

If I run the application, choosing "Local machine" or any Windows Phone emulator, I see "BEFORE": the line that changes the innerHtml of the div is not executed.

Otherwise, if I execute the html file outside of Visual Studio, in a browser window, I see "AFTER": this is true for all browsers, with a little exception in the behavior of Internet Explorer 11: in this case I see the message "Internet explorer restricted this web page from running scripts or activex controls", and when I click "allow the content" I see "AFTER".

Why this very simple script does not work in Visual Studio? Is it a matter of security restrictions, like in IE? And why I don't see any message at all in Visual Studio about the issue? How can I solve this problem in Visual Studio?

like image 867
Sean Avatar asked Oct 18 '15 10:10

Sean


People also ask

How do you access the DOM from JavaScript?

Accessing a DOM element By ID: JavaScript can find HTML elements in the DOM based on the "id" of the element. The document object provides a method "getElementById()" to accomplish this task.

How do you access elements using DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What are DOM elements in JavaScript?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

Which method is used to add components or elements to the DOM?

The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .


1 Answers

I've tested your code. It's true but you should write your code inside of javascript files. Just move window.onload at the begining of the default.js.

like image 78
kaya Avatar answered Sep 19 '22 00:09

kaya