Im trying do this basically:
var tr = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(document.createTextNode('<input class="param" type="text" name="dummy" value="fred"/>'));
tr.appendChild(td);
but it just displays the input... as normal text, how do I insert it so that it works as i require..?
im guessing its the createTextNode that needs to be changed?
Cheers
You could either
td.innerHTML = '<input class="param" type="text" name="dummy" value="fred"/>';
or
var ip = document.createElement( 'input' );
ip.className = 'param';
ip.type = 'text';
ip.name = 'dummy';
ip.value = 'fred';
td.appendChild( ip );
EDIT
ie won't allow the type of a form element to be changed dynamically. I'm pretty sure this only applies when the element already has a type and has already been inserted into the DOM. Best to check though. If it doesn't work use method 1
Try using innerHtml property of element.
That is try using td.innerHtml = "<input ...../>"
Meouw has the right idea. You're creating a text node in your example, and what needs to be done is create a dom element.
This is also another case where jQuery could simplify your code. What you were attempting to do by adding the element as an html string can be done with the jQuery html( val ) function:
http://docs.jquery.com/Attributes/html#val
Basically, to apply this technique with your given example, you would include the jQuery library on your page and write the following line:
$("#someTable").html('<tr><td><input class="param" type="text" name="dummy" value="fred"/></td></tr>');
You can also create any html element on the fly and string together attributes and event handlers in one line as in the following example:
http://www.peterbe.com/plog/creating-dom-element-with-jquery
var textbox = $("<input type='text'></input>").attr('name','dummy').addClass('param').val('fred');
$("#someTableCell").append(textbox);
Related
I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.
I am a beginner in javascript. I'm trying to add a function to generate new form elements using javascript, on a page that's generated in php.
The code works in creating new <tr>, <td>, <input type="text"> html elements. However when I try to create buttons using css styles, I find that the styles are lost from the tags.
if(document.createElement)
var tr = document.createElement("tr");
var input = document.createElement("input");
// If NS is passed, should become NS[2] etc
input.id = field+"["+count+"]";
input.name = field+"["+count+"]";
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
var td=document.createElement("td");
var newContent = document.createTextNode("NS");
td.appendChild(newContent);
tr.appendChild(td);
td=document.createElement("td");
td.appendChild(input);
tr.appendChild(td);
var btnDel=document.createElement("a");
btnDel.class="btn btn-primary";
btnDel.onclick = "addField(\'nameservers\',\'NS\',10);" ;
var btnText=document.createElement("span");
btnText.class="btn-label";
btnText.innerHTML="Add";
btnDel.appendChild(btnText);
td.appendChild(btnDel);
tr.appendChild(td);
field_area.appendChild(tr);
}
The produced code shows:
<a><span>Add</span>
</a>
</td>
instead of what I expect:
<a onclick="addField('nameservers','NS',10);" class="btn btn-primary">
<span class="btn-label">Add
</span>
</a>
What am I doing wrong? What's the proper way of passing all html attributes using the script?
For the on click
Instead of trying to output this into the HTML, why not do this in pure Javascript, using the addEventListener method?
element.addEventListener('click', function() {
addField('nameservers','NS',10);
}, false);
This approach is known as non-obtrusive Javascript, and it's actually quite a desirable attribute when developing a website.
For the class
As mentioned, use className and not class.
class usually precedes the declaration of as new class, and can't be used like an attribute, in the same way that you can't call a variable var.
Use className= instead of class=. So it will be like:
btnDel.className="btn btn-primary";
It is because the class word is reserved word in JavaScript.
I recently posted some code on Code Review Stack Exchange
https://codereview.stackexchange.com/questions/8783/how-can-i-improve-performance-for-my-javascript-table-class
My code would populate an HTML table with values from an object in JavaScript
In the answer I received, it was suggested that I use the DOM to add rows to my table without using .innerHTML or jQuery. I would like to do this, but I don't know how.
My code looks like this:
var html = ... // code to get html
$(tbody).html(html);
How can I get the rows in the variable html into my table body without using innerHTML or jQuery.
I think the suggestion was probably that you use .innerText instead of .innerHTML when placing text string contents in an element (either pre-existing, or one you're creating on the fly). It's just safer to do. The reason being: if somehow in your retrieval of the contents you get a string that has something like "<script> //do something bad </script>" in it, that potentially dangerous script will be executed when appended to the DOM using .innerHTML. However, if you use .innerText it will just be placed in the DOM as a string, and not be evaluated as a script to run.
If you have an HTML string, your don't want to parse it yourself like Inerdial pointed it out in the comments.. Let the browser parse it for you with innerHTML/jQuery.
I will show you how to do plain DOM manipulation though:
var thediv = document.createElement('DIV');
thediv.style.backgroundColor = 'white';
thediv.appendChild(document.createTextNode('some text'));
document.getElementById('someElement').appendChild(thediv);
That's the basics, you can create tables and table rows and insert them in that fashion.
Why not use jQuery or innerHTML is another question.
EDIT: added some text to the div
Thanks
It seems that if you use the approach you're trying:
var html = '<tr><td>This is a div</td></tr>';
$(tbody).html(html);
You will be using innerHTML. To avoid this, you need to create DOM nodes instead:
var cell = document.createElement('td');
var row = document.createElement('tr');
var tbody = document.getElementsByTagName('tbody')[0];
row.appendChild(cell);
tbody.appendChild(row);
Of course this will append an empty td to a tr and append that to the tbody. To place content in the cell, you'd still have to use innerHTML:
var cell = document.createElement('td');
cell.innerHTML = "This is text inside of the created 'td' DOM node.";
var row = document.createElement('tr');
var tbody = document.getElementsByTagName('tbody')[0];
row.appendChild(cell);
tbody.appendChild(row);
JS Fiddle demo.
Using jQuery, this can be condensed to:
var cell = $('<td />').text("This is text inside of the created 'td' DOM node.");
var row = $('<tr />');
var tbody = $('tbody:first');
row.append(cell).appendTo(tbody);
JS Fiddle demo.
A link to a comparison of the approaches ('vanilla' JavaScript against jQuery), at JS Perf.
I’m using AJAX to append data to a <div> element, where I fill the <div> from JavaScript. How can I append new data to the <div> without losing the previous data found in it?
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by #BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
Beware of innerHTML, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();
"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.
http://api.jquery.com/append/
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
An option that I think is better than any of the ones mentioned so far is Element.insertAdjacentText().
// Example listener on a child element
// Included in this snippet to show that the listener does not get corrupted
document.querySelector('button').addEventListener('click', () => {
console.log('click');
});
// to actually insert the text:
document.querySelector('div').insertAdjacentText('beforeend', 'more text');
<div>
<button>click</button>
</div>
Advantages to this approach include:
Does not modify the existing nodes in the DOM; does not corrupt event listeners
Inserts text, not HTML (Best to only use .insertAdjacentHTML when deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS)
Flexible; the first argument to .insertAdjacentText may be beforebegin, beforeend, afterbegin, afterend, depending on where you'd like the text to be inserted
you can use jQuery. which make it very simple.
just download the jQuery file add jQuery into your HTML
or you can user online link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
$("#divID").append(data);
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html() without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
Why not just use setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
thisDiv.attrName;
I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.