lisovaccaro
lisovaccaro

Reputation: 33956

Simple condition that returns true if document.activeElement = ""

I need to know if the selected element has an ID.

What am I doing wrong?

  var selected = document.activeElement;
  if (selected.id = "") {
  document.getElementById('test3').innerHTML= "is blank";    
  }

Thanks

Upvotes: 1

Views: 6045

Answers (2)

jfriend00
jfriend00

Reputation: 707366

Obviously, you can't test equality with =. It requires == (identity with type conversion) or === (identity without any type conversion).

In any case, it's a bit safer to do the comparison this way:

var selected = document.activeElement;
if (selected && selected.id) {
  document.getElementById('test3').innerHTML= "is blank";    
}

if (selected.id) will be true if either selected.id == null or selected.id == undefined or selected.id == "" which will cover more cases than just if (selected.id == "").

Upvotes: 3

Digital Plane
Digital Plane

Reputation: 38264

You are setting the id instead of comparing it. Change = to ==.

var selected = document.activeElement;
if (selected.id == "") {
  document.getElementById('test3').innerHTML= "is blank";    
}

Upvotes: 3

Related Questions