Best way to get HTML + text from an array

5

Function I am 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 text and HTML ( <a href="">... Veja mais!</a> ) from the array, the HTML is coming as normal text and not in HTML format.

    
asked by anonymous 23.10.2017 / 18:18

2 answers

4

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

$().text() treats the content as 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><divid="div1"></div>
<div id="div2"></div>
    
23.10.2017 / 18:50
2

The .html(param) function when passed a string HTML as a parameter sets the HTML content of each element in the corresponding element set, that is, unlike . text () which only allows the manipulation of a text to .html () allows the manipulation of a HTML element.

Follow the example below:

$(".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); Atribuirá somente um TEXTO
        $(this).html(res); //Criará um link
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="push-description-top">
  
</div>
    
23.10.2017 / 19:04