mardi 25 mai 2021

Combine .each link contain function to one if statement

I am trying to look up all the "a" tag on the whole page, so I am using the "each" function. And would like to have a way to combine all the link contain conditions as one js, so it won't look so messy. But I guess I cannot use "a[href*="something"]" in the if statement? If not, what will that be? I tried "indexOf", but keep throw me an error, so inside each, cannot use "index of"?

$('a').each(function() {
    if ($('a[href*="typeone"]')) {
      var linktitle = $(this).attr('title');
      $(this).attr('title', 'Typeone: ' + linktitle);
    } else if ($('a[href*="typetwo"]')) {
      var linktitle = $(this).attr('title');
      $(this).attr('title', 'Typetwo: ' + linktitle);
    } else if ($('a[href*="typethree"]')) {
      var linktitle = $(this).attr('title');
      $(this).attr('title', 'Typethree: ' + linktitle);
    } else {
      var linktitle = $(this).attr('title');
      $(this).attr('title', 'Other: ' + linktitle);
    }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Aucun commentaire:

Enregistrer un commentaire