1

There are a few similar questions on Stack but I think mine is the result of some syntax error on my part. Anyway, I'm building a lightbox in javascript and want to dynamically set the absolute position (left % css) to be half of the width of the element.

This is a snippet from the code. Full code is here http://jsfiddle.net/Yab3Q/4/

var modal = document.getElementById(btnId+"-modal");
var modalChildren = modal.childNodes;

for (var x = 0; x<modalChildren.length; x++){
    if (!(modalChildren[x].className === "lightBox")){
        var childWidth = modalChildren[x].offsetWidth;
        var halfWidth = childWidth / 2;
        modalChildren[x].style.left = halfWidth + "px";
    }
}

The line modalChildren[x].css.left = halfWidth + "px"; is returning "Uncaught TypeError: Cannot set property 'left' of undefined". However, modalChildren[x].className and modalChildren[x].offsetWidth; both return the expected values, so I'm unsure why I can view but not update the css here.

1
  • Do you mean this line? ` modalChildren[x].style.left = halfWidth + "px";` Commented Dec 15, 2012 at 6:36

2 Answers 2

1

You try to alter the style properties of the following elements:

0: <div>
1: #text
2: <img>
3: #text

You can see this list for yourself by typing

console.log(modalChildren) 

since a textNode does not have a style property, an error is thrown

Sign up to request clarification or add additional context in comments.

2 Comments

Got it. What's the best way to exclude the #text from the if statement I have? I tried if (!(modalChildren[x].className === "lightBox") && !(modalChildren[x].nodeType == "#text")) but to no avail
just try this: if (modalChildren[x].style)
1

text node has no style property: log and check:

for (var x = 0; x<modalChildren.length; x++){
            console.log(modalChildren[x]);
            console.log(modalChildren[x].style);
            if (!(modalChildren[x].className === "lightBox")){
                var childWidth = modalChildren[x].offsetWidth;
                var halfWidth = childWidth / 2;
                modalChildren[x].style.left = halfWidth + "px";
            }
        }

Take a look at node types: http://www.javascriptkit.com/domref/nodetype.shtml

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.