Best way to get child nodes
Sounds like you're overthinking it. You've observed the difference between childNodes
and children
, which is that childNodes
contains all nodes, including text nodes consisting entirely of whitespace, while children
is a collection of just the child nodes that are elements. That's really all there is to it.
There is nothing unpredictable about either collection, although there are a couple of issues to be aware of:
- IE <= 8 do not include white space-only text nodes in
childNodes
while other browsers do - IE <= 8 includes comment nodes within
children
while other browsers only have elements
children
, firstElementChild
and friends are just conveniences, presenting a filtered view of the DOM restricted to just elements.
Finding child element of parent with JavaScript
The children
property returns an array of elements, like so:
parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]
There are alternatives to querySelector
, like document.getElementsByClassName('parent')[0]
if you so desire.
Edit: Now that I think about it, you could just use querySelectorAll
to get decendents of parent
having a class name of child1
:
children = document.querySelectorAll('.parent .child1');
The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.
Get child node index
you can use the previousSibling
property to iterate back through the siblings until you get back null
and count how many siblings you've encountered:
var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.
Please note that in languages like Java, there is a getPreviousSibling()
function, however in JS this has become a property -- previousSibling
.
Use previousElementSibling or nextElementSibling to ignore text and comment nodes.
Proper way to select child nodes in D3
d
is the data object and i
the index. Both are not d3 instances that provide access to any of the d3 select
functions.
Try this:
myelement.on('mouseenter', function(d,i) {
d3.select(this).select('circle');
});
Getting elements by tag among given element childNodes
With an iteration, you can check the tag name of the element like that :
var child = yourElement.children;
var childrensSpan = [];
for(var i = 0; i < child.length; i++){
if(child[i].tagName === "SPAN") childrensSpan.push(child[i])
}
console.log(childrensSpan);
Fiddle : http://jsfiddle.net/Paesk/
Of course, yourElement
is your parent element and "SPAN"
is the tag you are searching for.
Get child nodes where parent node has an ID
Try this:
var txt='<prices><car id="1"><name>Toyota</name><price_day>250</price_day></car> <car id="2"><name>Opel</name><price_day>100</price_day></car></prices>';
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
var x=xmlDoc.getElementsByTagName("car");
for (i=0;i<x.length;i++)
{
if(x[i].getAttribute('id')=='1')
{
alert(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
}
}
Fiddle http://jsfiddle.net/BKazh/2/
How to get child element by class name?
Use doc.childNodes
to iterate through each span
, and then filter the one whose className
equals 4
:
var doc = document.getElementById("test");
var notes = null;
for (var i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].className == "4") {
notes = doc.childNodes[i];
break;
}
}
How to get all childNodes in JS including all the 'grandchildren'?
This is the fastest and simplest way, and it works on all browsers:
myDiv.getElementsByTagName("*")
Scala: get child nodes count in XML
(XML \\ "c" \ "_").length
gives 9 (Count of all "c" children)
((XML \ "c")(0) \ "_").length
gives 3 (Count of first "c" children)
Related Topics
How to Force Angular2 to Post Using X-Www-Form-Urlencoded
Should an Async API Ever Throw Synchronously
Window.Open and Pass Parameters by Post Method
Change Form Values After Submit Button Pressed
How to Make <Input Type="Date"> Supported on All Browsers? Any Alternatives
Convert Text to Image Using JavaScript
"Pointer-Events: None" Does Not Work in IE9 and Ie10
D3.Js - V3 and V4 - Enter and Update Differences
Positioning Divs in a Circle Using JavaScript
Saving and Loading an Image from Localstorage
Angular2:Render a Component Without Its Wrapping Tag
How to Inherit from a Class in JavaScript
Javascript/Jquery: Test If Window Has Focus
Best JavaScript Solution for Client-Side Form Validation and Interaction
How to Swipe Top Down Jquery Mobile