Shady Nawara
Shady Nawara

Reputation: 502

Check whether a div exists and redirect if not

How do I check whether a certain div exist on my page and if not, redirect the visitor to another page?

Upvotes: 17

Views: 56395

Answers (4)

havardhu
havardhu

Reputation: 3616

You can use jQuery for that

if ($("#mydiv").length > 0){
    // do something here
}

Read more here: http://jquery.com/

Edit: Fixed the error pointed out in the comment below. Sorry, busy day at work and got too trigger happy.

Upvotes: 1

Lee Crossley
Lee Crossley

Reputation: 1280

You will need to use JavaScript to be able to check if the element exists and do the redirect.

Assuming the div has an id (e.g. div id="elementId") you can simply do:

if (!document.getElementById("elementId")) {
    window.location.href = "redirectpage.html";
}

If you are using jQuery, the following would be the solution:

if ($("#elementId").length === 0){
    window.location.href = "redirectpage.html";
}

Addition:

If you need to check the content of divs for a specific word (as I think that is what you are now asking) you can do this (jQuery):

$("div").each(function() {
    if ($(this).text().indexOf("copyright") >= 0)) {
        window.location.href = "redirectpage.html";
    }
});​

Upvotes: 40

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

What differenciate this particular div from others on the page ?

If it has an ID, you can to this with document.getElementById:

var div = document.getElementById('the-id-of-the-div');
if (!div) {
    location = '/the-ohter-page.html';
}

You can also check the content of the div:

var div = document.getElementById('the-id-of-the-div');
var html = div.innerHTML;

// check that div contains the word "something"
if (!/something/.test(html)) {
    location = '/the-ohter-page.html';
}

Upvotes: 3

Harry Joy
Harry Joy

Reputation: 59660

Using jQuery you can check it like this:

if ($("#divToCheck")){ // div exists } else { // OOPS div missing }

or

if ($("#divToCheck").length > 0){
  // div exists
} else {
  // OOPS div missing
}

or

if ($("#divToCheck")[0]) {
  // div exists
} else {
  // OOPS div missing
}

Upvotes: 5

Related Questions