Gergő Horváth
Gergő Horváth

Reputation: 3705

Why getting a node element's style attribute returns false in javascript?

It's a bit long way why I'm asking this question.

function topMag(x) {
  elem = x;

  do {
    elemTop += elem.offsetTop;
    elem = elem.offsetParent
  }
  while (elem != "[object HTMLBodyElement]");

  elem = x;
};

With the function, I want to get the target element's height from the top. But the code isn't working, because if the target element's position is fixed, the element's offset Parent returns false. Not a big deal, the problem has a simple solution. But the only way this solution works, is when the style is set inline. If the position is set to an element with external or internal style sheet (or isn't set, so the position is static), the style.position returns false. My question is 2fold: Why does this happen, and how to solve it? Thanks for the answers.

function topMag(x) {
  elem = x;

  if (elem.style.position == "fixed") {
    elemTop = elem.offsetTop
  };

  else {
    do {
      elemTop += elem.offsetTop;
      elem = elem.offsetParent
    }
    while (elem != "[object HTMLBodyElement]");

    elem = x;
  }
};

Upvotes: 1

Views: 229

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65796

Accessing the style property of an element returns a CSSStyleDeclarations Object that, itself has properties for each of the CSS properties. However, when the style property is used, this object only picks up properties that have been set as inline styles via the style attribute in HTML or the style property in JavaScript (since HTML attributes map to JavaScript properties, the style property is a reflection of the style attribute and the style attribute is where inline styles are set).

For properties that have been set via a selector in a stylesheet, you must use window.getComputedStyle() to retrieve a CSSStyleDeclarations Object that reflects all of the CSS property values after being computed by the CSS layout/rendering engine.

Lastly, you have some syntax issues with your semicolons that need to be addressed, so, your function would look something like this:

function topMag(elem) {
  // Get the offsetTop property value:
  var ost = elem.offsetTop;

  // Check the position
  if (getComputedStyle(elem).position === "fixed") {
    elemTop = ost;
  } else {
    do {
      elemTop += ost
      elem = elem.offsetParent;
    } while (elem !== "[object HTMLBodyElement]");   
  }
}

Upvotes: 3

Related Questions