Steven Steven - 1 year ago 41
Javascript Question

How to avoid javascript retrieving values from non-existing elements

Update: clarified question (I hope)

I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.

In case of A, I ouput element "Foo".

In case of B, I output element "Bar".

Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).

I've looked at using the


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

I'm also using jQuery. So one solution could be using this:

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

Using the above methods, makes me having to check each element before trying to retrieve any values.

The "ideal" solution would be to get values based on user privileges. E.g:

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

This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.

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

The other solution would be adding a value to the cookie.

setcookie("userPriv", "A");

Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.

I'm looking for opinions on which method is "the best way" to accomplis this.

Answer Source

Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.

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

The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.

Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)

<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 hidden input. It seems cleaner to me, more along the unobtrusive lines