简体   繁体   中英

Firefox JavaScript error “undefined” (div Id).style in console

I am using JavaScript to resize and reposition page elements to fit the browser window. My code works perfectly in Chrome, Safari, and Internet Explorer 9 , but breaks in Firefox. The console gives me two errors: "TypeError: sidebar.style is undefined" and "TypeError: content.style is undefined" .

I certainly do have two divs with Id's named "sidebar" and "content" and am using both of the Id's successfully in CSS. In what way could they be undefined?

Adding to the confusion, a duplicate of this script is used on another page in the site, but with another Id specific to that page. It works with no problems. What might be causing this problem?

You don't show your code, but given the wording of your question and the title with "(div Id).style in console" I suspect you are trying to simply reference the elements directly in your JavaScript by using the ids as if they were variables. Some browsers do allow this, though it can cause problems if you also have variables of the same name. Some browsers do not allow this.

You should get a reference to the elements using document.getElementById() :

document.getElementById("sidebar").style
// NOT
sidebar.style

Of course you don't want to have to keep calling document.getElementById() over and over for the same element, so you can create a variable that keeps a reference to the element:

var theSidebar = document.getElementById("sidebar");
// then later to do something to the element's style
theSidebar.style.color = "blue";

Note also that JavaScript code that tries to reference elements from your HTML will only work if run after those elements have been parsed when the page loads. So you need your code to either be in a script element included after the element(s) it accesses or to use a document ready or onload handler to delay executing the code until the whole page is parsed.

I ultimately resolved the issue by simply changing the ID of the div. Evidently Firefox disliked 'sidebar' as an ID for some reason. No other changes to the code were necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM