Compare part of url with contents of div

44 Views Asked by At

One of the site i am using recently implanted suggestion search so currency showing so many unrelated trash.

​Trying to hide all div that not contain part of url.

sample url pattern

https://urll.com/lib/search/textquery

div part

    <a class="text-secondary group-hover:text-primary" href="https://urll.com/lib/F52dk" alt="F52dk">click here for F52dk link
</a>

Not very familiar with jquery and try to wrote two scripts but none of them worked.


    if ($("exampledivname").has(":contains('window.location.pathname.split("/").pop()')").length) {
    
    } else {
       hide();
    
        }
var lastpart = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)
var alttt = $('a').attr("alt");
if (lastpart === alttt) {
  alert("it's there!!");
}

jsfiddle.net/yd61v753

1

There are 1 best solutions below

0
Karan On

You can try like below. Explanation is provided in comment.

$(document).ready(function() {

  // Get last part of the URL, Use .filter(x => x.length > 0) retrieve second last value in case URL ends with /. 
  let lastpart = window.location.pathname.split('/').filter(x => x.length > 0).pop();

  // Added below static value for testing only, since URL won't work with fiddle here.
  lastpart = 'F52dk';

  // Apply logic only if lastpart has valid value
  if (lastpart) {
    // Add class example-class to div on which you want to apply the logic.
    // Loop over those divs with .each() Ref : https://api.jquery.com/jQuery.each/
    $('.example-class').each((index, d) => {
    // 
      // $(d).find() will check for elements inside given element.
      // attribute-ends-with-selector : 'a[href$="String To Find"]' will search for any <a> element with href value ends with string provided inside "".
      // Ref : https://api.jquery.com/attribute-ends-with-selector/ & https://api.jquery.com/category/selectors/
      if ($(d).find('a[href$="' + lastpart + '"]').length) {
        $(d).show();
      } else {
        $(d).hide();
      }
    });
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
  <div class="thumbnail group">
    <div class="example-class relative aspect-w-16 aspect-h-9 rounded overflow-hidden shadow-lg">
      <a href="https://urll.com/dm/lib/F52dk" alt="F52dk">
      </a>
      <a href="https://urll.com/dm5/en/F52dk" alt="F52dk">
        <span class="absolute bottom-1 right-1 rounded-lg px-2 py-1 text-xs text-nord5 bg-gray-800 bg-opacity-75">
01:18
</span>
      </a>
    </div>
    <div class="example-class my-2 text-sm text-nord4 truncate">
      <a class="text-secondary group-hover:text-primary" href="https://urll.com/dm5/en/F52dk" alt="F52dk">
F52dk transform out-of-the-box convergence
</a>
    </div>
  </div>
</div>