EaBangalore EaBangalore - 10 months ago 42
Node.js Question

how to to put values into array if class is present

i have a list of values inside a div having class="price" iam intrested to push
values into array if class is present otherwise/ 'not present'.

the div pattern is .mainDiv>span, .price sometime pattern will be .mainDiv > span
sometime .mainDiv > .price

so how to push price value into array if class="price" is present.

DOM tree is below.

<div class="mainDiv">
<div class="price">$2000</div>
<div class="mainDiv">
<div class="price">$300</div>
<div class="mainDiv">
<span>abcdsnndsjdjnd</span> <!-- observe here price is not there -->

I am using code like this

var arr = [];
if ($(this).hasClass('price')){
arr.splice(i, 0, $(this).text());
} else {
arr.splice(i, 0, 'no price');

Please help me thanks in advance


Firstly you're using hasClass() on the .mainDiv itself, when the .price element is a child. You could use has() or find().length to get the element.

You could also make this simpler by using map() to create your array. Try this:

var arr = $('.mainDiv').map(function() {
    return $(this).has('.price') ? $(this).text() : 'no price';