DavSev DavSev - 1 month ago 7
jQuery Question

jQuery check if one ul contains elements from another

I have two lists

What I want to do is to get the text of every element from the first list, if the text matches the value of an element in the second list than color it in that select option second list.

this are the two lists:

list No 1

<div id="rssedituserdata">
<li>1444</li>
<li>1445</li>
</div>


List No 2

<div class="form-item form-item-labeled" id="edit-field-building-no-value-wrapper">
<select name="field_building_no[value][]" multiple="multiple" class="form-select" id="edit-field-building-no-value">
<option value="1444">a</option>
<option value="1445">b</option>
<option value="1446">c</option>
<option value="1447">d</option>
<option value="1448">e</option>
<option value="1449">f</option>
<option value="1450">g</option>
</select>
</div>


this is what i did so far....

$("#edit-field-building-no-value-wrapper option").each(function() {
var building = $(this).text();
console.log(building);


$("#rssedituserdata>li").each(function(building) {
if ($(this).has(building)) {
building.css('color', 'red');
}
});
});

Answer

Use a attribute selector to select the options that have the value attribute equal with the text of the list items:

    $("#rssedituserdata>li").each(function(i,v) {
       $('option[value="'+$(v).text()+'"]').css('color', 'red');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rssedituserdata">
<li>1444</li>
<li>1445</li>
</div>


<div class="form-item form-item-labeled" id="edit-field-building-no-value-wrapper">
<select name="field_building_no[value][]" multiple="multiple" class="form-select" id="edit-field-building-no-value">
    <option value="1444">a</option>
    <option value="1445">b</option>
    <option value="1446">c</option>
    <option value="1447">d</option>
    <option value="1448">e</option>
    <option value="1449">f</option>
    <option value="1450">g</option>
</select>
</div>

to remove element that are not in the list do the following : add a class to the elements in the list and remove all option that don't have that class

$("#rssedituserdata>li").each(function(i,v) {
       $('option[value="'+$(v).text()+'"]').addClass('dont-remove').css('color', 'red');
    });
$('option:not(.dont-remove)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rssedituserdata">
<li>1444</li>
<li>1445</li>
</div>


<div class="form-item form-item-labeled" id="edit-field-building-no-value-wrapper">
<select name="field_building_no[value][]" multiple="multiple" class="form-select" id="edit-field-building-no-value">
    <option value="1444">a</option>
    <option value="1445">b</option>
    <option value="1446">c</option>
    <option value="1447">d</option>
    <option value="1448">e</option>
    <option value="1449">f</option>
    <option value="1450">g</option>
</select>
</div>