[Vuejs]-Vue JS: Show div if its class matches another class on the page

2👍

Wow, you’re completly violating VueJS…

I would suggest something like the following:

new Vue({
  el: "#app",
  data: {
    x: "Apples",
    y: [
      "Apples",
      "Apples, Bannanas, Pears",
      "Something else"
    ]
  },
  methods: {
    filteredDivs: function() {
      return this.y.filter(el => {
        let elementsInCurrentElement = el.split(',');
        for (let temp of elementsInCurrentElement) {
          if (temp.trim() === this.x) {
            return true;
          }
        }
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    {{x}}
  </div>
  <div v-for="element in filteredDivs()">
    {{element}}
  </div>
</div>

1👍

The following function will do what you intend… Note that you will want to make the code more robust by adding error checking to ensure that there is exactly one element with class X; It would probably be better to use a specific element ID to find the filter source div as opposed to using a class. But that is up to you.

function myCriteria() {
  var elementListX = document.getElementsByClassName("X");
  var elementListY = document.getElementsByClassName("Y");

  var elementX = elementListX[0];
  for (var index = 0; index < elementListY.length; index++) {
    var element = elementListY[index];
    if (element.innerText.indexOf(elementX.innerText) >= 0) {
      element.style.display = "block";
    } else {
      element.style.display = "none";
    }
  }
}
<html>

<body onLoad="myCriteria()">
  <div class="X">Apples</div>

  <div class="Y">Apples</div>
  <div class="Y">Apples, Bannanas, Pears</div>
  <div class="Y">Bannanas, Pears</div>
  <div class="Y">Pears</div>
</body>

</html>

0👍

Like this?

This is only JS solution, You should not do this in Vue (and you haven’t shown Vue app code at all). But as your attempt is only JS here is how you can do it as example:

This goes from basis you have multiple X, and search for Y, not other way around, as you did not specify that, but did mention in example.

[...document.querySelectorAll('.X')].forEach(x => {
  [...document.querySelectorAll('.Y')].forEach(y => {
    y.innerText.includes(x.innerText) ? y.style.display = "block" : y.style.display = "none"
  })
})
<div class="X">Apples</div>

<div class="Y">Apples</div>
<div class="Y">Apples, Bannanas, Pears</div>
<div class="Y">Bannanas, Pears</div>
<div class="Y">Pears</div>

Also: getElementsByClassName() with two classes getelementsbyclassname does not take 2 arguments.

Leave a comment