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 .
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.
src
property with JavaScript. –
Proviso SPAN
to store URIs to images and i need it to be a SPAN and not some javascript array , so what does "NOT VALID" mean here ? is it forbidden to put whatever you want into a SPAN
? what if i wanted to put the following text "xcserw4dadw3" will the HTML code of the page be "Not Valid" then ? –
Marijo <span id="h">http://x.com?d=d&x=x</span>
is not valid HTML, for the same reason <span>&</span>
isn't, just like <span><</span>
isn't. Special characters (<
, >
and &
) do not represent themselves. &
signifies the beginning of an html entity, and the character &
must therefore be represented as &
. So in your case, <span id="h">http://x.com?d=d&x=x</span>
would be valid. –
Spradlin 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
© 2022 - 2024 — McMap. All rights reserved.
&
is the more correct way to represent&
in HTML, not just in body text, but even inside the contents of an href. – Psychosocial