innerHTML gives me & as & !
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 &s
???
Thank you .
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("<img src='myimage.jpg'>");
// 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
精彩评论