简体   繁体   中英

Get innerHTML from dynamically added script tag

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript" id="embeddedScript">
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("id", "scriptData");
    script.src = "DynamicText.jsp";
    script.onload = function() {
        alert(x);
        alert(document.getElementById("scriptData"));
        alert(document.getElementById("scriptData").innerHTML);
        alert(document.getElementById("embeddedScript").innerHTML);
    };
    document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
</html>

DynamicText.jsp

x="Hello World!"

The first alert gives Hello World!

The second alert gives [Object HTMLScriptElement]

I expected the third alert to give the value of x="Hello World!" But it displays an empty value.

But for fourth alert I could see the entire text which was inside the script tag with an id "embeddedScript"

Reason?

The js script tag you created scriptData has no content between its tags. It is simply linking to a js resource to execute. It would come out looking like this

<script type="text/javascript" id="scriptData" src="DynamicText.jsp"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM