Open In App

How to find all links with an hreflang attribute using jQuery ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to find all links with a hreflang attribute. The hreflang is an attribute that tells search engines the relationship between pages in different languages on your website. To find all links with an hreflang attribute using jQuery, you can use the attribute selector $(‘[hreflang]’). This will select all elements that have the hreflang attribute defined. To specifically select only <a> elements with the hreflang attribute, you can use the tag selector in combination with the attribute selector: $(‘a[hreflang]’).

You can use this attribute in the following three ways.

  • As a link in the HTML head of the page(<head>).
  • In the HTTP header (example PDFs)
  • On the XML sitemap

You can find all links with an hreflang attribute on your page using the attributeContainsPrefix selector.

attributeContainsPrefix selector: This selector is used to select elements that have the specified attribute with a value either equal to a given string or starting with that string.

Syntax:

jQuery( "[attribute|='value']" )

$( "a[hreflang|='en']" ) 

Example 1: In the following examples, we first find the hreflang and then highlight it using CSS properties. The hreflang attribute with a value ‘en’ gets highlighted with the red dotted border.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        a {
            display: inline-block;
        }
    </style>
    <script src=
    </script>
</head>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <a href="example.html" hreflang="en">GFG</a>
    <a href="example.html" hreflang="en-UK">
        Computer Science
    </a>
    <a href="example.html" hreflang="english">
        will not be outlined
    </a>
 
    <script>
        $("a[hreflang|='en']")
            .css("border", "3px dotted red");
    </script>
 
</body>
</html>


Output:

href lang = en

Example 2: 

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        a {
            display: inline-block;
        }
    </style>
    <script src=
</head>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <a href="example.html" hreflang="en">Database</a>
    <a href="example.html" hreflang="en-UK">
        Computer Networks
    </a>
    <a href="example.html" hreflang="english">
        will not be outlined
    </a>
 
    <script>
        $("a[hreflang|='en']")
            .css("border", "3px solid green");
    </script>
 
</body>
</html>


Output:

hreflag=en image2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads