Decompose a variable that contains HTML

0

Hello, I have a query, how can I decompose a variable that contains the following?

    <div>
        <strong>titulo aqui</strong>
        <br>
        <text>Texto aqui</text>
    </div>

What I would like is to be able to get the contents of the strong in one variable and the content of the text in another without the html tags

var titulo = titulo aqui

var text = Texto aqui

is there any way?

    
asked by Ignacio Fuentes 31.10.2018 в 05:26
source

3 answers

1

I'll give you the alternative with pure JS.

You only have to use getElementsByTagName and take the first element of array . Note that this would be worth only if you have a <strong> element and a <text> element. If you had more you would have to go through the array and go doing the corresponding treatment.

let strongTag = document.getElementsByTagName("strong")[0];
let textTag = document.getElementsByTagName("text")[0];
console.log(strongTag.innerText);
console.log(textTag.innerText);
<!DOCTYPE html>
<html>
<body>
<div>
<strong>titulo aqui</strong>
<br>
<text>Texto aqui</text>
</div>
</body>
</html>
    
answered by 31.10.2018 в 12:36
0

The idea of what you are looking for would be that the texts are inside some tag with some id to get the value with JQuery (in the case that you are using it) and store it in the variables as you request. It would be something like this:

    <div>
        <strong id='titulo'>titulo aqui</strong>
        <br>
        <text id='texto'>Texto aqui</text>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        var titulo = $('#titulo').text();
        var texto = $('#texto').text();
        console.log(titulo);
        console.log(texto);
    </script>

The console.log () are for you to check that the variables contain the value of the tags.

    
answered by 31.10.2018 в 05:47
0

Using jQuery is not complex, you can use jQuery(''selector'') .

//Defino una variable con el contenido de tu ejemplo
var html =   "<div>"+
              "<strong>titulo aqui</strong>"+
              "<br>"+
              "<text>Texto aqui</text>"+
            "</div>";

//Obtengo el texto de la etiqueta strong dentro de la variable html
var Titulo = jQuery('strong',html).text();
//Obtengo el texto de la etiqueta text dentro de la variable html
var Text = jQuery('text',html).text();

//Muestro el resultado
console.log(Titulo);
console.log(Text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you are starting in jQuery, it would be highly recommended this reading, to learn to use the selectors, which will help you a lot!

    
answered by 31.10.2018 в 05:47