views:

27

answers:

2

Hi Everyone

I have this javascript in a classic asp page...

I need to find out if x.name is undefined or has a value:

x=document.getElementsByTagName("meta")[i];
if (String(x.name) != "undefined" && String(x.name) != ""){
document.write(""+x.name +": "+x.content+"<br><br>");
}

I am not sure why it is throwing an error:

document.write(""+x.name +": "+x.content+"<br><br>");

if x.name or x.content is false?

Thanks

A: 

It's throwing an error because you are in all likelihood trying to write the value of an element before it has been instantiated. Until your page loads none of its elements exist or and henceforth they cannot be referenced.

Robusto
I am sure the element does not exists in some cases... I know it does not exists and that is why I do not want to show it...
Gerald Ferreira
+1  A: 

To check for undefined:

if (typeof x !== 'undefined') {
  if (x.name) {
    document.write(x.name + ': ' + x.content + '<br><br>');
  }
}

Now, I don't know what you're trying to do with that document.write() call, so that might cause problems too, but the above will make sure you only do it when "x" exists and has a non-empty "name" attribute.

Pointy
This is not part of the main question but how can I do it without document write
Gerald Ferreira
Hi Pointy Thanks for the solution it works perfect.. It actually solved a second problem for me as well... The x (has two values) x.name and x.content in some cases 1 value will be true and another value will be false... Your solution makes it false even if one value is true and the other false... This is exactly what I needed!
Gerald Ferreira
Well I'm not sure what exactly you want to do with `document.write()`, but one possibility is to use `innerHTML` to stuff your dynamic content into an empty element on the page. Thus the page would have something like `<span id="meta-name"></span>`, and then you'd find that element (with `getElementById()`) and set its "innerHTML" property to what you're writing into the page.
Pointy