I want to get all children of <p>.
HTML:
<p id="p">nodlist is an <i> ordered <b>collection of node</b> objects that are </i>children of the current element.<font color="blue"> If the element</font> has no children, then contains no node.</p>
JavaScript:
var childrens = [];
function getchilds(node){
if(node.nodeType == 1){
var childnodes = node.childNodes;
for(i=0; i<childnodes.length; i++){
var child = childnodes[i];
if(child.nodeType == 1)
getchilds(child);
}
}else
childrens.push(node);
}
var childnodes = document.getElementById('p').childNodes;
for(i=0; i<childnodes.length; i++){
getchilds(childnodes[i]);
}
but childrens[] is:
0 : nodlist is an
1 : ordered
2 : collection of node
3 : objects that are
4 : has no children, then contains no node.
children of the current element and If the element have missed, and when I add <a> element like link to p tag, the script gets stuck in an infinite loop.
Looks like you're using a global variable i for the loops which means you're going to miss elements when returning from an inner function call. Change it to
for(var i=0; i<childnodes.length; i++){
in both loops.
Related
<script>
var c = document.body
var e = document.createElement("div");
e.className = "box";
for (var i=0; i<=2; i++) {
c.appendChild(e);
}
</script>
When I run this for loop, only one div is created in the browser. However,
if I add a console.log(e) into the loop and run it on a console, (i.e)
<script>
var c = document.body
var e = document.createElement("div");
e.className = "box";
for (var i=0; i<=2; i++) {
console.log(e);
c.appendChild(e);
}
</script>
the output is
"<div class='box'></div>"
"<div class='box'></div>"
"<div class='box'></div>"
I know that I can correct the issue by declaring the variables inside the for loop, but I'm not sure why the first code above would not work?
I suppose this entry from MDN covers that:
The Node.appendChild() method adds a node to the end of the list of
children of a specified parent node. If the given child is a reference
to an existing node in the document, appendChild() moves it from its
current position to the new position (there is no requirement to
remove the node from its parent node before appending it to some other
node).
This means that a node can't be in two points of the document
simultaneously. So if the node already has a parent, the node is first
removed, then appended at the new position
It's what you expect of a variable.
e is a reference to the created div, not the actual constructor. So appendChild can only add the element once to the DOM, otherwise it would replace it to the new position, since an element is unique within the DOM. Of course console.log will list the same reference trice.
The solution is, as you said, to create a different element within the loop:
for (var i=0; i<=2; i++) {
const e = document.createElement("div");
c.appendChild(e);
}
document.window.appendChild(c);
<script>
var div = "<div class='box'></div>";
for (var i = 0; i <= 2; i++) {
document.queryselector("body").innerHTML += div
}
</script>
I'm trying to pass string elements from an array myArr while selecting the div it should go into with a forEach loop, so that each of the four div elements below has a corresponding string element from the array.
I'm having some trouble with it, because I'm selecting the divs with a querySelectorAll method. Help would be appreciated. This code below is just a sample of what I'm working on, so it can't be altered too much.
HTML
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
JS
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
numberDivs.forEach(function(el) {
el.innerHTML = "new number";
for (var i = 0; i < myArr.length; ++i) {
el.innerHTML = myArr[i];
}
});
Right now, it's (el) only passing through the last element in the array to all divs, instead of the corresponding one.
I think is this what you want:
numberDivs.forEach(function(el, i) {
el.innerHTML = myArr[i];
});
This assumes they are of equal length, and won't overwrite each element's HTML like your code is currently doing.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
for (var i = 0; i < myArr.length; i++) {
numberDivs[i].innerHTML = myArr[i];
}
You're issue was you had a for loop going across all the elements, then another for loop going across your array. The inner for loop, the one for you're array, would always end at the last element, therefore each object - the divs - ended at the final element of that array.
http://jsfiddle.net/a8zrkejo/
Quick fix, if you're certain the total count of the array is same as the number of divs
then loop the array only and use the index of each element to access the div.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
myArr.forEach(function(value, Index) {
numberDivs[Index].innerHTML = value
});
How can i build a nodelist, which is reference to the selected node?
Example document.querySelectorAll('tr') returns a nodelist contains all the tr element node references on page.
I`m writing methods, to return element nodelist references by search criteria.
But if i using insertBefore, appendChild, etc... this function will remove the nodes from the elements.
Example i have a 4x4 table, and i want to return the first 2 rows:
var nl = document.createDocumentFragment();
el = document.querySelectorAll('tr');
for ( var a = 0; a < 2 && a < el.length; a++)
{
nl.appendChild(el[a]);
}
console.log(nl);
This nl returns the first 2 rows of the table, but it will removes from the document. Removed from the DOM and append to nl as child.
I want to retrieve only the node(s) reference like querySelectorAll as a list, not as documentFragment childNodes.
Any idea how to archieve this?
If you don't want to move things around in the DOM, don't use the methods that move things around!
var nl = new Array();
var el = document.querySelectorAll('tr');
for ( var a = 0; a < 2 && a < el.length; a++)
{
nl.push(el[a]);
}
I have a webpage that contains ASP.NET panels and JavaScript that gets all of the components in the page:
var items = Sys.Application.getComponents();
I need to get the name/ID of each of the elements in the items variable. I have tried the following code: (but it doesn't work)
for (var item in items)
{
alert(item.name);
}
What attribute of 'item' contains the name/ID? How can I modify the above code to do this?
Use the get_name() and get_id() functions instead.
var items = Sys.Application.getComponents() ;
for( var i = 0 ; i < items.length; i++ ) {
var item = items[i];
var id = item.get_id();
var name = item.get_name();
}
http://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationGetComponentsMethod.aspx
None. item is the key/property so you want items[item].name.
However, if items is an array, using for..in to iterate over it is completely inappropriate. In this case use for(var i = 0; i < items.length; i++) and var item = items[i] inside the loop body.
I'm working on a website which uses a tree structure made the following way : a list is created and if an element of this list is itself a list then it is append to the first list using appendChild. The big list is put in a div named 'tree'.
I would like to access the content of the div 'tree' and go through the nodes to display them.
I've tried to code it several ways but it doesn't work, does someone has any idea how to do it ?
Edit (my code was too long)
This function iterates through a DOM tree. You can pass it a callback that takes the parent and child element too:
_SU3.treeIterate = function(parent, callback) {
var children = _SU3.getChildren(parent);
for (var i = 0; i < children.length; i++) {
var child = children[i];
callback(parent, child);
_SU3.treeIterate(child, callback);
}
};
_SU3.getChildren = function(parent) {
var children = new Array();
var childNodes = parent.childNodes;
if (childNodes == null)
return children;
for (var i = 0; i < childNodes.length; i++) {
var child = childNodes[i];
if (child.tagName == "li" || child.tagName == "LI") {
children.push(child);
}
}
return children;
};
Note: in this example the getChildren() function only finds "li" items. Amend as necessary.
If you think you will need several other functions on the tree, I suggest you to have a look on jsTree