0

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?

1 Answer 1

1

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"]; } 
Sign up to request clarification or add additional context in comments.

4 Comments

One would think the OP had a reason for the more restrictive CSS selectors, no?
@caasjj What do you mean?
my bad @caasjj updated the selectors to match the original ones
$("div.row.text-secondary")[0] is not a valid condition. Not sure why length didn't work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.