Attribute value is URI encoded on set

Asked by At

I want to set an attribute of a DOM element using element["attribute"], but the value is URI encoded. For instance, if the value is q=test&r=123&s=456 and after I append it into the DOM, the value becomes q=test&r=123&s=456.

Now, view RENDERED source, or Copy HTML of the script tag using Firebug...

Please copy paste the code below on a new HTML file for your valuable investigation.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="javascript: injectTag();">Inject Tag</a>
    <div id="status"></div>
    <script>
        var injectTag = function () {
            var scriptTag = document.createElement("script");
            scriptTag["src"] = "http://www.google.com/search?q=US+Geological+Survey&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a";
            scriptTag["type"] = "text/javascript";

            var head = document.getElementsByTagName("head")[0];
            head.appendChild(scriptTag);
            document.getElementById("status").innerHTML = "Now, view <b>RENDERED source</b>, or <b>Copy HTML</b> of the script tag using Firebug...";
        }
    </script>
</body>
</html>

With thanks and Regards,
Munim

1 Answers

1
Tomalak On Best Solutions

What you see is exactly what should happen.

The value is not URI-encoded, though. It is HTML-escaped.

All data (data is: attribute values and text) within an HTML page must be HTML-escaped (& becomes &amp; in the source code, < becomes &lt;, and so on). Most browsers are forgiving if you forget to do this, but it is wrong nevertheless.

If you add data dynamically, the DOM just follows that rule and HTML-escapes the data for you.