[javascript] jQuery: If this HREF contains

Why can't I get this to work??

$("a").each(function() {
    if ($(this[href$="?"]).length()) {
        alert("Contains questionmark");
    }
});

Ps.: This is just at simplifyed example, to make it easier for you to get an overview.

This question is related to javascript jquery

The answer is


It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

Try this:

$("a").each(function() {
    if ($('[href$="?"]', this).length()) {
        alert("Contains questionmark");
    }
});

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

$("a").each(function() {
    if (this.href.indexOf('?') != -1) {
        alert("Contains questionmark");
    }
});