1

I'd like to set a variable to equal the text of a substring. Specifically, if a[href] begins with "download.php", I'd like to set the variable "elm" to the value of a[href], after the 19th character.

if ("a[href^='download.php']") {
    var elm = $('a[href]'.substring(19));
};

I've tried using .text() and .html(), but can't get it working. Can someone point out my errors? Many thanks.

2
  • 3
    "a[href^='download.php']" is a string which is a truthy value, you are doing something fundamentally wrong here. Commented Oct 11, 2013 at 17:40
  • A boolean element needs to be inside of an if statement, not a string Commented Oct 11, 2013 at 17:40

2 Answers 2

2
var a = $("a[href^='download.php']");
if (a.length) {
  var elm = a.attr("href").substring(19);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You dont need your if statement, since you are passing a string which is a truthy value.

To get the value of href atributte use $.attr

var elm = $("a[href^='download.php']").attr('href').substring(19);

and if you want to check if exists any element who match with [href^='download.php'] use

var el = $("a[href^='download.php']");
if(el.length) {
    var elm = el.first().attr('href').substring(19);
}

2 Comments

No, if there is no element that matches, it will break the script. since attr('href') will be undefined. That is the whole point of check in OP's code.
Better but again why do you need to create jq object again. You can cache it. I mean a lot like the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.