Select <a> which href ends with some string using jQuery

Given some anchor tags, i.e., <a>, let's see which href attribute does ends with some specific string using jQuery.
Submitted by Pratishtha Saxena, on September 07, 2022

Prerequisite: Adding jQuery to Your Web Pages

An anchor tag helps to define and declare a hyperlink for an HTML web page. We can provide the links using the href attribute of the anchor tag. Once defined, then the user can click on the displayed on the screen and go to the target page.

Now, in case you need to filter out some of the <a> tags amongst all others using a common string, here is a way for it.

The jQuery selector - [attribute$=value] will help to get the filtered anchor tags. Over here, the attribute name and the specified value can be declared. It will pick up those elements which have a particular value as their attribute value.

Syntax:

$("[attribute$='value']");

The element name can also be defined in front of it so that it gets an idea of which elements to be traversed. If we need to filter the input tag with some specific attribute value then we need to mention input ahead of it. Since here we are working for the anchor tags, hence, we'll be mentioning 'a' in front.

Let's see the following example for better understanding. We want to get the anchor tags whose href ends with '.com/'. Hence, the elements that match this will get highlighted.

jQuery example to select <a> with href ends with some string

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>	
  </head>
  
  <body>
    <h2>Select < a > Which href Ends With Some String</h2>
    <p>Click the button to know which anchor tag's URL contains 'com' at the end.</p>
    <button>Click Here</button>
    <hr>
    Links:
    <br>
    <h3>
      <span>1] </span><a href="https://www.google.com/">Google</a><br><br>
      <span>2] </span><a href="https://www.microsoft.com/en-in/">Microsoft</a><br><br>
      <span>3] </span><a href="https://www.wikipedia.org/">Wikipedia</a>
    </h3>
    <hr>
    <h3 id="myH"></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            var get = $("a[href$='.com/']").css({"font-size":"30px", "color":"Red"});
        });
    });
  </script>
</html>

Output:

Example: Select 'a' which href ends with some string





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.