Kenny
Kenny

Reputation: 339

Struggling with jQuery conditional selectors

I've been trying to figure this out for hours now.

I want to select all anchor links that begin with the attribute 'http: //localhost' and exclude all links that contain 'wp-admin' in them.

I can select all links that begin with 'http: //localhost' with this:

$internalLinks = $("a[href^='http://localhost']")

This is what I have so far for excluding the 'wp-admin' links, but it doesn't work:

$internalLinks = $("a:not[href*='wp-admin']a[href^='http://localhost']"),

What am I missing?

Upvotes: 2

Views: 134

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173542

I want to select all anchor links that begin with the attribute http:/localhost and exclude all links that contain 'wp-admin' in them.

Given the relative complexity of your condition I would consider using filter() instead:

$('a').filter(function() {
    // starts with 'http://localhost' and does not contain 'wp-admin'
    return this.href.indexOf('http://localhost') == 0 && 
       this.href.indexOf('wp-admin') == -1;
});

Doing everything in a single expression doesn't mean you avoid evaluating all anchors on the page, so you might as well make it easier on yourself.

Upvotes: 3

Jordan Running
Jordan Running

Reputation: 106027

You've nearly got it. The selector you're looking for is this:

a[href^='http://localhost']:not([href*='wp-admin'])

The two mistakes you made were 1) repeating the tag name (a) and 2) forgetting the parentheses for the :not() selector.

Upvotes: 4

rynhe
rynhe

Reputation: 2529

Try this

 $internalLinks = $("a[href^='http://localhost']").not("a[href*='wp-admin']");

Example

http://jsbin.com/burobako/1/edit

Upvotes: 1

Agha Umair Ahmed
Agha Umair Ahmed

Reputation: 1020

use somthing like this

$("a:not([href^=wp-admin])");

and see this link

jQuery selector question. Select all nodes that do NOT START with (string)

Upvotes: 0

Related Questions