Best way to get text + HTML from an array

Asked

Viewed 109 times

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>) of the array, HTML is coming as normal text and not in HTML format.

  • With jQuery I don’t think there’s any other way, and if you have it would be bizarre.

  • it happens that it is returning as text element

2 answers

4


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

$().text() treats 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>

  • What is the difference?

  • 1

    I edited the reply @Laérciolopes

  • 1

    Cool, I found this very good example: http://jsfiddle.net/hossain/sUTVg/

2

The function .html(param) when past a string HTML as parameter defines the content HTML of each element in the corresponding set of elements, that is to say, different from .text() which only allows manipulation of a text to .html() allows manipulation of an element HTML.

Below is an example:

$(".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>

<div class="push-description-top">
  
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.