Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery filter :contains for a link (a href="#")

Tags:

jquery

filter

I have a link that is currently:

a href="#" 

but soon the client will change the link to

a href="something"

When the link becomes something I would like to use jQuery to change the css, but I am not sure how to write a filter for an attribute (href="")...

like image 690
redconservatory Avatar asked Apr 13 '11 18:04

redconservatory


People also ask

How to use contains method in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

How to filter value in jQuery?

The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.

How to find element by text in jQuery?

The :contains() selector in jQuery is used to select elements containing the specified string. The text must have a matching case to be selected. Syntax: A string of text to look for. It's case-sensitive.

Which is the correct jQuery selector to select selected elements having href attribute value equals?

jQuery [attribute$=value] Selector The [attribute$=value] selector selects each element with a specific attribute, with a value ending in a specific string.


3 Answers

Here are two options that you can use to compare your href attribute:

Href is empty:

$('a[href=""]') or $('a[href="#"]')

Href isn't empty:

$('a[href!=""]') or $('a[href!="#"]')

When comparing attributes, jQuery offers several operators for comparisions:

 = Is Equal
!= Is Not Equal
^= Starts With
$= Ends With
*= Contains

More on jQuery Selectors here.

like image 63
Rion Williams Avatar answered Oct 15 '22 17:10

Rion Williams


Here's a selector for an anchor with an href not equal to hash:

$('a[href!="#"]')
like image 37
Eli Avatar answered Oct 15 '22 18:10

Eli


A quick read on jQuery selectors should do the trick (as mentioned by Rionmonster above). I'd just like to note that you can also check for elements with a specific attribute (which I expect you'll actually need?) by doing something like

$('a[href]')

This finds <a> elements that have a defined href attribute, whether that be a hash or anything else. Good for filtering out clickable anchors.

like image 38
Richard Neil Ilagan Avatar answered Oct 15 '22 16:10

Richard Neil Ilagan