javascript – Best way to get text + HTML from an array

Question:

Function I'm using:

$(".push-description-top").each(function() {

    var text = $(this).text();
    var carac = text.length;

    if (carac > 0) {
        var query = text.split(" ", 14);
        query.push('<a href="">... Veja mais!</a>');
        res = query.join(' ');
        $(this).text(res);
    }

});

When pulling the text and HTML ( <a href="">... Veja mais!</a> ) from the array, the HTML is coming in as normal text and not in HTML format.

Answer:

To insert text with HTML tags in an element you can use $(this).html(res); instead of $(this).text(res);

$().text() treats the content as a string while $().html() treats the string as HTML.

Example

$("#div1").html('<a href="/">Diga </a><b>ola</b>');
$("#div2").text('<a href="/">Diga </a><b>ola</b>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>
<div id="div2"></div>
Scroll to Top