I have HTML tag content:
<p id="horaInicial">2018-07-23 16:40:16</p>
Inside a JavaScript variable, I want to know how to access the value: 2018-07-23 16:40:16 and put inside another variable!
Can anyone help?
I have HTML tag content:
<p id="horaInicial">2018-07-23 16:40:16</p>
Inside a JavaScript variable, I want to know how to access the value: 2018-07-23 16:40:16 and put inside another variable!
Can anyone help?
Create an element that interprets as DOM and use textContent
, for example:
var foo = '<p id="horaInicial">2018-07-23 16:40:16</p>';
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = foo;
var bar = tmpDiv.querySelector("#horaInicial").textContent;
console.log(bar);
If by chance you use jQuery you could simply use $()
combined with .text()
:
Of course importing jQuery just for this would be unnecessary consumption, so just do it if you already use jQuery for other things
var foo = '<p id="horaInicial">2018-07-23 16:40:16</p>';
var bar = $(foo).text();
console.log(bar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
NotethatifyouhaveimagesorotherresourcesdependingonthesourceofthestringthatcontainstheHTMLyourcodemaybecomeunsafe(itwillnotbeunsafe,theyareisolated/specificcases),seeapostrelatedtothis:
So if you're unsure of the data source of this string, type it from outside sources to avoid attacks use DOMParser
:
Supported browsers:
Example:
function createDOM(str) {
return new DOMParser().parseFromString(str, "text/html");
}
var foo = '<p id="horaInicial">2018-07-23 16:40:16</p>';
var tmpElement = createDOM(foo);
var bar = tmpElement.querySelector("#horaInicial").textContent;
console.log(bar);
If it were jQuery it would have to combine:
function createDOM(str) {
return new DOMParser().parseFromString(str, "text/html");
}
var foo = '<p id="horaInicial">2018-07-23 16:40:16</p>';
var bar = $("#horaInicial", createDOM(foo)).text();
console.log(bar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can use the jquery .text()
function, which will return the content of the element you want.
Example:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>varconteudo="<p id=\"horaInicial\">2018-07-23 16:40:16</p>";
$(function () {
var outra_variavel = $(conteudo).text();
alert(outra_variavel);
});
</script>
</head>
</html>