简体   繁体   中英

Adding Values to a DOM element after the element has been created

I'm looking over some pretty extensive code for a web page that is generated from XML/XSL and then has Javascript generate the layout on the fly. What I am having troubles with is that it seems IE (v.10 specifically) is showing that elements are Empty Text Nodes if there is no value, and then regular text (no editable field) if there is a value.

This seems to change the behavior of to be just straight un-editable text.

From what I can see, the first step is for the Javascript to generate elements via the DOM

input = document.createElement("input");

input.setAttribute("id", "blah");
input.setAttribute("type", "text");

Then it will append it to the parent. Then what seems to happen is that a function is executed that runs through the page again and inserts any values that these fields have.

input.value = "Hello World";

Chrome and Firefox will display the input fields properly with their fields populated, but IE10 will only show the value as if it was just plain text.

I've never worked with this sort of web page generation and hoping someone might be able to help me figure this out so I can troubleshoot this. Changing the way this works (at the time) is not an option so I'm trying to correct it so that IE is happy too.

Thanks

This specific code sequence works in all browsers I've tried it in (Chrome, IE, Firefox):

var elem = document.createElement("input");
elem.type = "text";
elem.id = "test";
document.body.appendChild(elem);
elem.value = "This is some text";

If your exact code is deviating from this, then you should examine the differences or post your exact sequence of code that demonstrates the problem in IE so we have a better idea how to debug or advise.

You can see a working demo of this in any browser you want to try it in here: http://jsfiddle.net/jfriend00/z2FpP/

Things to watch out for in your code:

  1. Is any code setting .innerHTML of a parent which could be wiping out or resetting the child elements.
  2. Is any code setting .innerHTML of the input field itself. This should not be done. Code should use .value to set the text of the input field.
  3. Are there any code errors when the code runs in IE? Check the error console or debug console (hit F12 in IE to get to the debugger where you can see the error console).
  4. Are there any other attributes being set in the input field that might make it read-only instead of editable?

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