Search code examples
jqueryif-statementhyperlinkcontains

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);
    }
    });
<a href="https://typeone/something.html" title="the page name" target="_blank">this is the type one link</a>

<a href="https://typetwo/something.html" title="the page name" target="_blank">this is the type two link</a>

<a href="https://typethree/something.html" title="the page name" target="_blank">this is the type three link</a>

<a href="https://other/something.html" title="the page name" target="_blank">this is the other link</a>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Solution

  • You can use $(this).attr("href").indexOf.. to check if the href has somevalue or not depending on this change your title attribute.

    Demo Code :

    //target only a tag where href present.
    $('a[href]').each(function() {
      var linktitle = $(this).attr('title');
      //use indexof
      if ($(this).attr("href").indexOf("typeone") != -1) {
        $(this).attr('title', 'Typeone: ' + linktitle);
      } else if ($(this).attr("href").indexOf("typetwo") != -1) {
        $(this).attr('title', 'Typetwo: ' + linktitle);
      } else if ($(this).attr("href").indexOf("typethree") != -1) {
        $(this).attr('title', 'Typethree: ' + linktitle);
      } else {
        $(this).attr('title', 'Other: ' + linktitle);
      }
    });
    <a href="https://typeone/something.html" title="the page name" target="_blank">this is the type one link</a>
    
    <a href="https://typetwo/something.html" title="the page name" target="_blank">this is the type two link</a>
    
    <a href="https://typethree/something.html" title="the page name" target="_blank">this is the type three link</a>
    
    <a href="https://other/something.html" title="the page name" target="_blank">this is the other link</a>
    
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>