Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a jQuery selector to find links with # in href attribute?
You can try to run the following code to write a jQuery selector to find links with # in href. Here, ^ is used to find links starting with # in href.
The ^= attribute selector in jQuery matches elements where the specified attribute begins with the given value. When applied to anchor tags with href^="#", it selects all links that have href attributes starting with the hash symbol.
Example
Here's a complete example demonstrating how to select and handle clicks on links with # in href ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a[href^="#"]').click(function(){
alert('Success! Selected link starting with # in href.');
});
});
</script>
</head>
<body>
<a href="#demo" title="new">Demo</a><br>
<a href="/cplusplus/" title="C++ Tutorial">C++</a><br>
<a href="#section1">Section 1</a><br>
<a href="https://example.com">External Link</a>
</body>
</html>
In this example ?
- The selector
a[href^="#"]targets only anchor tags whose href attribute starts with "#" - Clicking on "Demo" or "Section 1" will trigger the alert
- Clicking on "C++" or "External Link" will not trigger the alert
Alternative Selectors
You can also use other attribute selectors for different matching patterns ?
// Contains # anywhere in href
$('a[href*="#"]')
// Ends with #
$('a[href$="#"]')
// Exact match
$('a[href="#specific-id"]')
Conclusion
Using jQuery's a[href^="#"] selector is an efficient way to target internal anchor links that begin with the hash symbol, making it useful for handling navigation within single-page applications or smooth scrolling implementations.
