最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - innerHTML gives me & as & ! - Stack Overflow

programmeradmin3浏览0评论

is there any JS (not jquery) method to get a URL from a span (ex: <span id="h">;x=x</span>)

without the &'s changed to &amp;s ???

Thank you .

is there any JS (not jquery) method to get a URL from a span (ex: <span id="h">http://x.com?d=d&x=x</span>)

without the &'s changed to &amp;s ???

Thank you .

Share Improve this question asked May 7, 2011 at 11:23 TeAmErTeAmEr 4,77313 gold badges66 silver badges107 bronze badges 1
  • As discussed in stackoverflow.com/q/62577621 this issue applies even inside an href, not just in body text. This might not be obvious since I think it is not as widely known that &amp; is the more correct way to represent & in HTML, not just in body text, but even inside the contents of an href. – MikeBeaton Commented Jun 26, 2020 at 10:40
Add a comment  | 

6 Answers 6

Reset to default 5
document.getElementById("h").textContent.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

(The replace calls are to trim leading and trailing white-space, which you may not need to do in your situation.)

If you want a text representation of the data get the .data from the textNode instead of the .innerHTML of the HTML element.

var element = document.getElementById('h');
var textNode = element.firstChild;
var URI = textNode.data;

Using .innerHTML will give you the data in a form encoded for HTML (and browsers will correct the error you have in the original markup)

Alternatively you can just use the following trick to decode the HTML entities:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

If your HTML looks like this:

<div onclick="testClick()" id="h">http://x.com?d=d&x=x</div>

You can have a function that will log the innerText:

  function testClick() {
    console.log(event.target.innerText)
  }

This will give you the value:

http://x.com?d=d&x=x

That is because the original HTML code is not valid, but was nevertheless correctly parsed as you intended, but printed as it should be. & is a special character in HTML, much like < is and you should encode them by the corresponding html entities.

The most straightforward way to get the literal text is with .innerText

Whereas using .innerHTML will encode chars like &.

So when I have a <span> like this:

<span id="h">http://x.com?d=d&x=x</span>

I can do this:

const spanSelector = document.querySelector("span #id")
const text = spanSelector.innerText
// text: http://x.com?d=d&x=x
发布评论

评论列表(0)

  1. 暂无评论