
Originally Posted by
Wizard13335
Umm, i really didn't understand what you said, so are you saying I should create a variable like var html would be the HTML code?
I'm not quite sure what you said there, either. 
Or are you saying that instead of putting the <p>, the text, and the </p> in seperate innerHTML's, I should put them in the same one?
In the code Twey posted, the markup will be added to the same innerHTML property, but it will be done one step at a time.
The first concatenation
Code:
e.innerHTML += '<p>';
will be considered to be an empty paragraph; reading the property should yield '...<p></p>'. The next concatenation
Code:
e.innerHTML += 'Text';
will add text after that paragraph, yielding '...<p></p>Text'. The final concatenation would be considered invalid markup because there is no opening p tag.
To avoid this, the concatenation should be a single, atomic operation. In the simplest case, this would be:
Code:
e.innerHTML += '<p>Text</p>';
If you are to build the string, then it's best to create an array, which is later joined and assigned:
Code:
var content = ['<p>',
'Text',
'</p>'];
if(condition) {
content.push('<p>Some more text</p>');
}
e.innerHTML += content.join('');
The reason for doing it this way is that direct string concatenation is relatively slow. Though the join method does indeed concatenate each array element, it does so in native machine code, which will be optimised and therefore quicker. The other reason is that the Array.prototype methods can add a lot of flexibility whilst building each part of the string.
Mike
Note that the Array.prototype.push method isn't implemented in earlier JScript versions, so it may need to be emulated:
Code:
if('function' != typeof Array.prototype.push) {
Array.prototype.push = function(v) {
var i = this.length >>> 0,
j = 0,
n = arguments.length;
while(j < n) {this[i++] = arguments[j++];}
return this.length = i;
};
}
Bookmarks