简体   繁体   中英

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

I am using code like this

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

Please help me thanks in advance

There are various issues in your code

  1. $(this).hasClass('price') - here working of hasClass() method is not as you expected like has() method. It's check the class for the selected element not for it's descentant. So use $(this).has('.price').length instead
  2. $(this).text() - retrives all the div text since you just need the price use $('.price', this).text() instead.


Use map() method in jQuery for make it optimized.

 // iterate aver all div var arr = $('.mainDiv').map(function(i) { // cache the `.price` element var $price = $('.price', this); // check `.price` element present or not // and based on that generate the element return $price.length ? $price.text() : 'no price'; // get the array from the generated jQuery object }).get(); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$2000</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$300</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <!-- observe here price is not there --> </div> 

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';
}).get();

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