user1665355
user1665355

Reputation: 3393

Get text of an element with jquery

I have this html and try to get the text (i.e. Brand:Adidas) from each <li class="col-xs-2">.

<div class="row text-secondary">
        <div class="col-xs-2">
            <ul class="row">
                <li class="col-xs-2">
                    Brand: 
                    Adidas
                </li>
                <li class="col-xs-2">
                    Colour: Black
                </li>
                <li class="col-xs-2">
                    Model:
                    New
                </li>
                <li class="col-xs-2">
                    Size: 
                    2 
                </li>

Like this:

if ($(".row.text-secondary")[0]){
    $('div.text-secondary div.col-xs-2 ul.row li.col-xs-2').each(function () {
    var Var1 = [];
    var Var2 = [];
    var Var3 = [];

    Var1 = $(this).text();
    Var2 = Var1.replace(/[\n\t\r]/g, "");
    Var3.push(Var2);
});
} else{
    var Var3 = ["NotAvailable", "NotAvailable", "NotAvailable","NotAvailable"];
}

But when I save to database I get blank values where if ($(".row.text-secondary")[0]) evaluates to true(also if I use if ($(".row.text-secondary").length). I only get correct answer if the conditions above evaluate to false, then I get NotAvalaible.

Does anyone know what I am doing wrong?

Upvotes: 0

Views: 34

Answers (1)

Daniel Rosano
Daniel Rosano

Reputation: 695

Use condition $(".row.text-secondary")!=null

Also Var1 and Var2 are strings not arrays

Var3 must be declared outside if block

Also, if you only want the value discarding the field name use

var Var2 = Var1.substring(Var1.indexOf(":") + 1).replace(/[\n\t\r]/g, "").trim();

instead of

var Var2 = Var1.replace(/[\n\t\r]/g, "");

First option will generate an array having ["Adidas", "Black", "New", "2"]

Hope it helps,

var Var3 = [];
if ($("div.row.text-secondary")!=null){
    $('div.text-secondary div.col-xs-2 ul.row li.col-xs-2').each(function () {
       Var1 = $(this).text();
       var Var2 = Var1.replace(/[\n\t\r]/g, "");
       Var3.push(Var2);
});
} else{
    Var3 = ["NotAvailable", "NotAvailable", "NotAvailable","NotAvailable"];
}

Upvotes: 1

Related Questions