Javascript createElement and appendchild in one step - javascript

i want to create an element and then append this with other elements in one step.
var header = document.createElement("thead").appendChild(document.createElement("tr"));
Why this Code outputs the only TR and not Thead?
When i use this code then its correct (thead + tr are there)
var header = CH.createElement("thead");
header.appendChild(CH.createElement("tr"));

Because Node.appendChild() returns the appended child...
var appendedChild = element.appendChild(child);
.. you can simply reference the child's parentNode like so (sample fiddle):
var header = document.createElement("thead")
.appendChild(document.createElement("tr"))
.parentNode; // the row's parentNode, i.e.: thead

#antisanity has a good solution. Another solution if your variable is pre-declared is to do this...
(header = document.createElement('thead'))
.appendChild(document.createElement('tr'));
This ensures that the assignment to header happens before the .appendChild().

Related

How can I get a clicked table row's TBODY?

I have a table with a few rows in it. Each row has an onclick event that is supposed to check the ID of the tbody element. This is stored in a variable for later use in a function.
Right now I have this snippet of jQuery:
var parentTable = $(this.parentNode)[0].id;
However, this only gets the ID of the entire table, not the tbody.
What's the best way to specify the ID of the tbody element?
First, your use of jQuery is wasted there. It would be written like this:
var parentTable = this.parentNode.id;
As far as getting the tbody id, assuming this is actually the row, your code should do it.
If you're actually getting the table, then that would be very unusual. The only way a tbody would not get created would be if you manually created the table from DOM creation methods, and left it out.
You may want to store that information in a data-tbody-id for each row, then when the user clicks on the row, the event object will hold that information.
You can use the following function
var tobody = parentTable.children('tbody')
You can use the following function
var tbody = $(this).parents("tbody");
var id = tbody.attr("id");

Appending all page <table>'s to respective <div> with pure Javascript

I have a website with a lot of posts with <table> and a new responsive layout.
When big table elements (lot of content) are opened on mobile devices, even with max-width: 100% or other CSS tricks, they get bigger than the screen.
The solution is append tables in a overflow: scroll <div>, but I can't edit all the post content, so I want to do that with pure Javascript. jQuery not allowed.
The objetive is:
Get all <table> elements of the page that are inside #post
Get their content
Append that content in a <div class="table_div"> in the same place that the <table> is
Remove old table elements (the ones that are not inside .table_div)
I already can get all content from table elements and remove the tables, but the part of the code that supposedly should append table content in .table_div do not work.
Part of my code so far:
var post = document.getElementById('post'),
tables = post.getElementsByTagName('table');
for(var i=0; i<tables.length; i++) {
var table = tables[i];
var table_content = table.innerHTML,
table_div = document.createElement('div');
tables.remove();
table_div.appendChild(table);
table_div.className = 'table_div';
document.appendChild(table_div);
}
Full code: http://jsfiddle.net/hmaesta/6mambr93/
Please, help with just pure Javascript. Thank you.
NodeList has two mode; static or live (ref When is NodeList live and when is it static?). Live means that changes in the DOM are reflected in the NodeList. And NodeList from getElementsByTagName is live. In your code, the length of tables is decremented everytime you remove #post table.
There is some way to solve the problem.
Use static NodeList. For example, querySelectorAll returns static one.
Map NodeList to Array. You can do this with var ts = []; Array.prototype.push.apply(ts, tables);. And after this, use ts instead of tables.
Keep length and order of NodeList. Use insertChild instead of appendChild to keep order and to keep <table> in #post.
Here is example.
var tables = document.querySelectorAll('#post table');
for(var i = 0; i < tables.length; i++) {
var table = tables[i];
var table_div = document.createElement('div');
table.parentElement.insertBefore(table_div, table);
table_div.className = 'table_div';
table_div.appendChild(table);
}
https://jsfiddle.net/boy48ngs/2/
Note: You do not need to remove <table> manually in this case. Element cannot has multiple parents and appendChild removes the element from current parent.
See this updated fiddle:
var post = document.getElementById('post'),
tables = post.getElementsByTagName('table');
for(var i=0; i<tables.length; i++) {
var table = tables[i];
var elem = document.createElement('div');
elem.className = 'table_div';
post.replaceChild(elem, table);
elem.appendChild(table);
}
I used the replaceChild method to first replace the table element with a newly created div. Then I append the original table element to that div.

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

Clone a div and make ID's of it it's children to be unique using javascript

I need to clone a div and after cloning all the elements within the div should have unique ids. I need to do this using javascript only and not jquery.
Can anyone help me please.
The following code clones an element, uses a recursive function to assign random id's to the cloned element and its children and appends it to the document body. Adjust to your needs. See also this jsfiddle
var someClone = someDiv.clone(true), children = someClone.childNodes;
someClone.id = Math.floor(1000+Math.random()*10000).toString(16);
reId(children);
function reId(nodes){
for (var i=0;i<nodes.length;(i+=1)){
var children = nodes[i].childNodes;
nodes[i].id = Math.floor( 1001+Math.random()*10000 ).toString(16);
if (children.length){
reId(children);
}
}
}
document.body.appendChild(someClone);

Moving the content of a DIV to another DIV with jQuery

http://www.frostjedi.com/terra/scripts/demo/jquery02.html
According to this link elements can be moved around by doing $('#container1').append($('#container2')). Unfortunately, it doesn't seem to be working for me. Any ideas?
See jsfiddle http://jsfiddle.net/Tu7Nc/1/
You must append not your div exactly, but your div's content(inner HTML) with Jquery's html() function.
HTML:
<div id="1">aaa</div>
<div id="2">bbb</div>​
Jquery:
$("#1").append($("#2").html());
Result:
aaabbb
bbb
It is best not to use html().
I ran into some issues due to html interpreting the contents as a string instead of a DOM node.
Use contents instead and your other scripts should not break due to broken references.
I needed to nest the contents of a DIV into a child of itself, here is how I did it.
example:
<div id="xy">
<span>contents</span>
</div>
<script>
contents = $("#xy").contents(); //reference the contents of id xy
$("#xy").append('<div class="test-class" />'); //create div with class test-class inside id xy
$("#xy").find(">.test-class").append(contents); //find direct child of xy with class test-class and move contents to new div
</script>
[EDIT]
The previous example works but here is a cleaner and more efficient example:
<script>
var content = $("#xy").contents(); //find element
var wrapper = $('<div style="border: 1px solid #000;"/>'); //create wrapper element
content.after(wrapper); //insert wrapper after found element
wrapper.append(content); //move element into wrapper
</script>
To move contents of a div (id=container2) to another div (id=container1) with jquery.
$('#container2').contents().appendTo('#container1');
You can also do:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) el1.appendChild(el2);
or as one statement, but not nearly as robust:
document.getElementById('container1').appendChild(document.getElementById('container2'));
Edit
On reflection (several years later…) it seems the intention is to move the content of one div to another. So the following does that in plain JS:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) {
while (el2.firstChild) el1.appendChild(el2.firstChild);
}
// Remove el2 if required
el2.parentNode.removeChild(el2);
This has the benefit of retaining any dynamically added listeners on descendants of el2 that solutions using innerHTML will strip away.
$('#container1').append($('#container2').html())
Well, this one could be an alternative if you want to Append:
document.getElementById("div2").innerHTML=document.getElementById("div2").innerHTML+document.getElementById("div1").innerHTML
if you wanted to rewrite contents:
document.getElementById("div2").innerHTML=document.getElementById("div1").innerHTML
I suggest a general approach with a function and jQuery:
function MoveContent(destId, srcId) {
$('#' + destId).append($('#' + srcId).contents().detach());
}
Content of a detached source node is appended to a destination node with call:
MoveContent('dest','src');
The first parameter is an id of a new parent node (destination), the second is an id of an old parent node (source).
Please see an example at: http://jsfiddle.net/dukrjzne/3/

Categories