简体   繁体   中英

Get text of an element with jquery

I have this html and try to get the text (ie 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?

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"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM