How do I get the contents of a JavaScript variable, which is an HTML tag?

3

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?

    
asked by anonymous 26.07.2018 / 20:00

2 answers

5

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>

DOMsecurityagainst

NotethatifyouhaveimagesorotherresourcesdependingonthesourceofthestringthatcontainstheHTMLyourcodemaybecomeunsafe(itwillnotbeunsafe,theyareisolated/specificcases),seeapostrelatedtothis:

  • Is "new DOMParser" safer than "document.createElement"?

So if you're unsure of the data source of this string, type it from outside sources to avoid attacks use DOMParser :

Supported browsers:

  • IE9 +
  • Safari 3.2 +
  • Chrome
  • Firefox

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>
    
26.07.2018 / 20:03
3

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>
    
26.07.2018 / 20:06