简体   繁体   中英

Extracting and Filtering Through Items on a List (JS)

I'm new to Javascript, so apologies if this is a bit of an amateur question.

I want to be able to search through a list and pick out several items based on properties listed with the target items.

For example, let's say I have the following list:

<ul>
<li> Round Red Apple </li>
<li> Round Purple Grape </li>
<li> Round Yellow Lemon </li>
<li> Long Yellow Banana </li>
<li> Long Green Cucumber </li>
<li> Round Red Tomato </li>
</ul>

Each item is listed with two properties. How would I, for instance, extract all the round items (Apple, Grape, Lemon, Tomato) and then display only these items (not the properties) elsewhere on a webpage, let's say in <div id="display"></div> ?

A little more complicated, how would I extract all the round items but only the ones that aren't also red (Grape, Lemon)?

Iterate through all li items and check the value using startsWith() function and store in separate array to process later.

Sample code using JQuery each() function :

var filteredItems = [];
$('li').each(function(i, item)
{
     var itemName = $(item).html();
     if(itemName.startsWith('Round'))
     {
          filteredItems.add(itemName);
     }
});

Now you can iterate filteredItems to append the items in desired div .

var container = $('#display');
$.each(filteredItems, function(i, item)
{
    container.append("<div>" + item + "</div");
});

EDIT:

You can do it in the same manner with JavaScript as well.

Try with :

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