2

I am trying to remove the value "banana" along with its element "li" in div column 1 if it doesnt match any value from column 2, but it shouldn't delete it if there is a matching value.

Not sure how can i achieve it though using javascript/jquery.

Here's what i have started so far:

<div class="container">
  <div class="column1">
  <ul>
  <li>apple</li>
  <li>banana</li> <!-- remove this element along with its value  if there is no matching content in column2 -->
  <li>orange</li>
  <li>lemon</li>
  </ul>
  </div>
  
  <div class="column2">
  <ul>
  <li>apple</li> 
  <li>banana</li> 
  <li>orange</li>
  <li>lemon</li>
  </ul>
  </div>
</div>

https://jsfiddle.net/Rgohing/wq3knp4z/

Appreciate any help that I can get.

Renz C. Gohing
  • 123
  • 1
  • 1
  • 9
  • document.evaluate("//li[text()='banana']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue != null – gaetanoM Jan 06 '21 at 14:39
  • thank you for responding, i tried to add it as a javascript but it doesn't seems work. do i need to use a library to make it work? – Renz C. Gohing Jan 06 '21 at 14:51

2 Answers2

2

Solution

  • To solve this first get all the values from the second list and store it in an array.

  • Then go over the elements of your first list and check if the second list contains this element if not then remove this element

let compArr = [];
document.querySelectorAll('.column2 > ul > li').forEach((val) => {
  compArr.push(val.childNodes.item(0).nodeValue);
});


document.querySelectorAll('.column1 > ul > li').forEach((val, ind) => {
  if(!compArr.includes(val.childNodes.item(0).nodeValue)){
    val.remove();
  }
});
<div class="container">
  <div class="column1">
  <ul>
  <li>apple</li>
  <li>banana</li> <!-- remove this element along with its value  if there is no matching content in column2 -->
  <li>orange</li>
  <li>lemon</li>
  </ul>
  </div>
  
  <div class="column2">
  <ul>
  <li>apple</li> 

  <li>orange</li>
  <li>lemon</li>
  </ul>
  </div>
</div>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
1

I think it is what you want.

 function check()
        {
            var fruitslist1 =document.querySelectorAll(".column1>ul>li");
            var fruitslist2 =document.querySelectorAll(".column2>ul>li");
            var find = false;
            var deletefruit = "banana";
            fruitslist2.forEach(fruitslist => {
                if(fruitslist.innerHTML==deletefruit) find = true;
            });
            
            if(!find)
            {
                fruitslist1.forEach(fruitslist => {
                    if(fruitslist.innerHTML==deletefruit) fruitslist.remove();
                });
            }        
        }
Sato Takeru
  • 1,669
  • 4
  • 12
  • 27