Why does the browser modify the ID of an HTML elem

2019-07-23 17:00发布

Say I've got this HTML page:

<html>
  <head>
    <script type="text/javascript">
      function echoValue(){
        var e = document.getElementById("/path/&#x24;whatever");
        if(e) {
          alert(e.innerHTML);
        }
        else {
          alert("not found\n");
        }
      }
    </script>
  </head>
  <body>
    <p id="/path/&#x24;whatever">The Value</p>
    <button onclick="echoValue()">Tell me</button>
  </body>
</html>

I would assume that the browser treats the ID-string /path/&#x24;whatever as simple string. Actually, it converts the &#x24; to it's rendered representation ($).

The javascript code however uses the literal string &#x24; to search for the element. So, the call document.getElementById fails and I never get hands on the value of the paragraph.

Is there a way to force the browser into using the given ID string literally?


Edit:
Of course I know that I don't have to escape the $. But the web page gets generated and the generator does the escaping. So, I have to cope with what I've got.

3条回答
The star\"
2楼-- · 2019-07-23 17:20

In the <p id="...">, the &#x24; sequence is interpreted as $, because it appears in an attribute and is treated as an HTML entity. Same goes for all other element attributes.

In the <script> element, HTML entities are not interpreted at all, so it shows up literally.

查看更多
走好不送
3楼-- · 2019-07-23 17:30

I'd suggest you to decode the HTML entity in your javascript code:

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
      function echoValue(){
        var decoded_string = $('<div />').html("/path/&#x24;whatever").text();
        var e = document.getElementById(decoded_string);
        if(e) {
          alert(e.innerHTML);
        }
        else {
          alert("not found\n");
        }
      }
    </script>
  </head>
  <body>
    <p id="/path/&#x24;whatever">The Value</p>
    <button onclick="echoValue()">Tell me</button>
  </body>
</html>
查看更多
We Are One
4楼-- · 2019-07-23 17:36

You could try decoding the javascript text without jQuery:

<html>
  <head>
    <script type="text/javascript">
      function decodeEntity(text){
        text = text.replace(/<(.*?)>/g,''); // strip out all HTML tags, to prevent possible XSS
        var div = document.createElement('div');
        div.innerHTML = text;
        return div.textContent?div.textContent:div.innerText;
      }
      function echoValue(){
        var e = document.getElementById(decodeEntity("/path/&#x24;whatever"));
        if(e) {
          alert(e.innerHTML);
        }
        else {
          alert("not found\n");
        }
      }
    </script>
  </head>
  <body>
    <p id="/path/&#x24;whatever">The Value</p>
    <button onclick="echoValue()">Tell me</button>
  </body>
</html>

JSFiddle: http://jsfiddle.net/phTkC/

查看更多
登录 后发表回答