thedethe
thedethe

Reputation: 87

Use jQuery to Check if Link exist

I have a pagination div that contains links to the previous page <span id="previous"><a href="www.site.com/page/1" >Previous</a>, and to the next page. On the first page, there will not be any link to the previous page.

Now I have 2 image buttons with front and back arrows. If the user clicks on these buttons, jQuery will take the link from the pagination div as mentioned above and redirect the user to these links. However if the pagination link does not exist like on the first page, clicking the previous button will not do anything.

My Code:

//img has id = info_rightclick_left

$("#info_rightclick_left").click(function() {
                    if($("#pagination_previous")) {
                        window.location  = $("#pagination_previous a").attr("href");
                    } else {
                        alert("NOO");
                    }
                });

The problem now is that it seems like whether or not #pagination_previous exists, clicking the image still redirects the user. In this case, on page 1, the user gets redirected to undefined

How can I solve this?

Upvotes: 2

Views: 5509

Answers (3)

iamserious
iamserious

Reputation: 5465

the answer in your question itself! just check for undefined like so:

$("#info_rightclick_left").click(function() {
   if($("#pagination_previous a").attr("href") !== "undefined") {
      window.location  = $("#pagination_previous a").attr("href");
    }
});

Upvotes: 2

Alex
Alex

Reputation: 7374

if($("#pagination_previous").length > 0) {

jQuery returns a list of captured elements, if it doesn't find any it will return an empty list, but still a list

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this.

$("#info_rightclick_left").click(function() {
                    if($("#pagination_previous").length) {
                        window.location  = $("#pagination_previous a").attr("href");
                    } else {
                        alert("NOO");
                    }
                });

Upvotes: 4

Related Questions