Update: clarified question (I really hope) Hi.

I am creating a wordpress plugin in Wordpress and I am outputting elements based on user rights A and B.

Just in case of the, I ouput element "Foo".
Just in case of B, I output element "Bar".

Up till now, I've not checked if the element is available before I attempt to retrieve the worthiness. This obviously provides me with a javascript error in certain browsers (like IE7).

I have checked out while using typeof() function:

if(typeof(element) == 'undefined') {
    //do something...
}

I am also using jQuery. So one solution might be by using this:

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

While using above techniques, makes me needing to check each element prior to trying to retrieve any values.

The "ideal" solution is always to get values according to user rights. E.g:

if (userPriv == A) {
    //get values from element 'Foo'
}

By doing this I'm able to check once, and perform the data gathering. The only real solutions I'm able to think about are setting the need for a concealed input element or use snacks.

<input type="hidden" id="userPriv" value="A" />

Another solution could be adding something towards the cookie.

setcookie("userPriv", "A");

Regrettably, this latter provides me with an alert message stating that cookie should be occur header (before html output). I believe it is because I am carrying this out in Wordpress.

I am searching for opinions which technique is "the easiest wayInch to accomplis this.

Forgive me if I am missing something, but checking for any DOM aspect in javascript is generally pretty easy.

var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
    //...
} else if (elementB) {
    //...
}

The bottom line is the if statement. getElementById will return nothing null when the element isn't found, that will evaluate to false within the if statement.


Alternatively, if you do not really wish to look for information on individual DOM elements, are you able to send the customers priv inside a hidden input and act on that? This is a cookie free method of delivering values clientside. Something similar to (edited to possess jQuery code rather)

<input type="hidden" id="userPriv" value="A" />
...

var priv = $('#userPriv').val();
if (priv == 'A') {
    //...
}

I'd still recommend checking for individual elements over checking a concealed input. It appears cleaner in my experience, more across the inconspicuous lines

You should use object as associative array:

var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();

For the reason that situation is a lot better to check and you'll avoid "spaghetti code".