Count how many elements in a div - javascript

I have a div with span inside of it. Is there a way of counting how many elements in a div then give it out as a value. For Example there were 5 span in a div then it would count it and alert five. In Javascript please.
Thank you.

If you want the number of descendants, you can use
var element = document.getElementById("theElementId");
var numberOfChildren = element.getElementsByTagName('*').length
But if you want the number of immediate children, use
element.childElementCount
See browser support here: http://help.dottoro.com/ljsfamht.php
or
element.children.length
See browser support here: https://developer.mozilla.org/en-US/docs/DOM/Element.children#Browser_compatibility

You can use this function, it will avoid counting TextNodes.
You can choose to count the children of the children (i.e. recursive)
function getCount(parent, getChildrensChildren){
var relevantChildren = 0;
var children = parent.childNodes.length;
for(var i=0; i < children; i++){
if(parent.childNodes[i].nodeType != 3){
if(getChildrensChildren)
relevantChildren += getCount(parent.childNodes[i],true);
relevantChildren++;
}
}
return relevantChildren;
}
Usage:
var element = document.getElementById("someElement");
alert(getCount(element, false)); // Simply one level
alert(getCount(element, true)); // Get all child node count
Try it out here:
JS Fiddle

Without jQuery:
var element = document.getElementById("theElementId");
var numberOfChildren = element.children.length
With jQuery:
var $element = $(cssSelectocr);
var numberOfChildren = $element.children().length;
Both of this return only immediate children.

i might add just stupid and easy one answer
<div>this is div no. 1</div>
<div>this is div no. 2</div>
<div>this is div no. 3</div>
you can get how many divs in your doc with:
const divs = document.querySelectorAll('div');
console.log(divs.length) // 3

With jQuery; checks only for spans inside a div:
JSFiddle
$(function(){
var numberOfSpans = $('#myDiv').children('span').length;
alert(numberOfSpans);
})();​

With jQuery you can do like this:
var count = $('div').children().length;
alert( count );​​​
Here's a Fiddle: http://jsfiddle.net/dryYq/1/

To count all descendant elements including nested elements in plain javascript, there are several options:
The simplest is probably this:
var count = parentElement.getElementsByTagName("*").length;
If you wanted the freedom to add more logic around what you count, you can recurse through the local tree like this:
function countDescendantElements(parent) {
var node = parent.firstChild, cnt = 0;
while (node) {
if (node.nodeType === 1) {
cnt++;
cnt += countDescendantElements(node);
}
node = node.nextSibling;
}
return(cnt);
}
Working Demo: http://jsfiddle.net/jfriend00/kD73F/
If you just wanted to count direct children (not deeper levels) and only wanted to count element nodes (not text or comment nodes) and wanted wide browser support, you could do this:
function countChildElements(parent) {
var children = parent.childNodes, cnt = 0;
for (var i = 0, len = children.length; i < len; i++) {
if (children[i].nodeType === 1) {
++cnt;
}
}
return(cnt);
}

The easiest way is to select all the span inside the div which will return a nodelist with all the span inside of it...
Then you can alert the length like the example below.
alert(document.querySelectorAll("div span").length)
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>

Related

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

get content of element after slicing his span

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

get value of child <div> of a parent <div>

<div id="parent">
<div id="child">
some-value
</div>
</div>
how do I get "some-value"?
I tried
var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.value;
document.getElementById("output").innerHTML=childval;
it outputs "undefined".
The value property only exists for form elements. If you want to get the content of any other elements, you can either use innerHTML [MDN] to get the content as HTML string, or textContent [MDN] resp. innerText [MSDN] to only get the text content without HTML tags.
childNodes [MDN] returns all child nodes, not only element nodes. That means, it also contains text nodes for example. The line break you have after <div id="parent"> is a text node as well. Hence, parent.childNodes[0] returns the text node which consists only of a line break.
If you want to get the first element node, you can either use children [MDN] (see browser compatibility), or iterate over the child nodes, testing what kind of node each of them is. 1 indicates an element node, 3 a text node:
var child = parent.firstChild;
while(child && child.nodeType !== 1) {
child = child.nextSibling;
}
There are also other ways to retrieve elements, e.g. with getElementsByTagName [MDN].
Or in your case, you can just use getElementById [MDN] to get a reference to both of the elements.
The problem is that parent <div> actuially has three children: a TextNode containing a new line after parent opening tag, the actual child <div> and yet another TextNode with newline after closing child tag. But hard-coding second item is a bad idea:
var parent = document.getElementById("parent");
console.info(parent.childNodes.length);
var child = parent.childNodes[1];
var childval = child.innerHTML;
I would suggest iterating over children and finding the actual child or using
parent.getElementsByTagName('div')
shorthand.
That's one of the reasons why people love jQuery so much:
$('#parent div').text()
var parent = document.getElementById("parent");
var child = parent.children[0];
var childVal = child.innerHTML;
document.getElementById("output").innerHTML = childVal;
DEMO : http://jsfiddle.net/bcqVC/2/
document.getElementById("output").innerHTML = document.getElementById("child").innerHTML;
This will solve your problem.
Using your way of approach try as shown below
var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.innerHTML;
document.getElementById("outPut").innerHTML=childval;
This will also solve your problem
To get all the <div> elements you can use:
var div_val=prompt("Enter a div to Get the Child Elements","");
var div_ele=document.getElementById(div_val).childNodes;
for (var i=0, max=div_ele.length; i < max; i++) {
alert(div_ele[i]); //All your Div Elements
}
try this way by this pointer.
var childs = document.getElementById('myDropdown').children; //returns a HTMLCollection
for (var indx = 0; indx < childs.length; indx++) {
// iterate over it
childs[indx].onclick = function() {
// attach event listener On Symbole Dive THIS .
this.style.color = "#ff0000";
// add to note form the symbole .
document.getElementById("Note_form").value += this.innerHTML;
}
}
<div class="dropdown">
<div id="myDropdown" class="dropdown-content">
<div>♥</div>
<div>☺</div>
<div>π</div>
<div>•</div>
<div>Σ</div>
<div>°</div>
<div>Ω</div>
<div>∞</div>
<div>×</div>
<div>÷</div>
<div>≥</div>
<div>≤</div>
<div>≠</div>
<div>®</div>
<div>©</div>
<div>¥</div>
<div>£</div>
<div>€</div>
</div>
</div>
<textarea id="Note_form" class="copy_erea" placeholder="The Content.." oninput="note_Edite(this.value);"></textarea>

Checking a parent container for children javascript

Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?
If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;
example = document.getElementById('div');
example.appendChild(aButton);
//loop to look for aButton / button type in example div
Cheers
Get the childNodes array, loop through and look for one matching your criteria ( input tag with type button, or possibly a button tag)
var children = example.childNodes;
for(var i = 0; i<children.length; i++){
if( children[i].tagName == "INPUT" && children[i].type=='button' ) {
example.removeChild( children[i] );
i--; //Decrement counter since we are removing an item from the list
}
}
Example: http://jsfiddle.net/BZMbk/3/
To get elements that are of a node type from a subset of the document you can simply do
document.getElementById('div').getElementsByTagName("button")
This will return any buttons under an element with the id of "div" (not a good name for an id btw)
You could use children and then loop through the children. For example if you have a div with the following set up:
<div id='div'>
<input type='button'>
<p>here</p>
</div>
You could then get the children an loop through them like this:
var example = document.getElementById("div");
var children = example.children;
alert(children.length);
for(var i = 0; i < children.length; i++)
{
alert(children[i].tagName);
}
And as to remove them it would be as simple as
example.removeChild( children[i] );

JavaScript: how to get img and div elements using getElementsByTagName

I have a tree structure as follows:
<ul id="theul275">
<li>
<div id="red"></div>
<img id="green" />
<script></script>
<div id="blue"></div>
</li>
</ul>
There are multiple UL's likes this on my page each with a different id. I am getting each UL by doing this:
var child = document.getElementById('theul' + id).getElementsByTagName('*');
the problem is, I only want to get the children of each ul which are either div's or img's.
Is there a way to get elements by multiple tag names?
I really appreciate any help because I am kind of new to JavaScript! Thanks!
Depending on what browsers you may to support, you could use the CSS selector interface.
document.getElementById('theul275').querySelectorAll('div, img');
Or use a library. There are plenty of options out there. I am familiar with two,
MooTools
$('theul275').getElements('div, img');
jQuery
$('#theul275').find('div, img');
Or get a reference to the li node, and loop through each node and check if the nodeName is DIV or IMG.
for (var i = 0, l = child.length; i < l; i++)
{
if (child[i].nodeName == 'DIV' || child[i].nodeName == 'IMG')
{
//...
}
}
You could use a iterative method for this.
var elemArray = document.getElementById('theul' + id).childNodes,
getChildByNodeName = function (elem, pattern) {
var childCollection = [],
re = new RegExp(pattern, 'g'),
getChild = function (elements) {
var childs = elements.childNodes,
i = 0;
if (childs) {
getChild(childs);
for (i = 0; i < childs.length; i += 1) {
if (childs[i].nodeName.match(pattern)) {
childCollection.push(childs[i]);
}
}
}
};
getChild(elem);
return childCollection;
}
var childs2 = getChildByNodeName(elemArray, '^(DIV|IMG)$'); // array of match elements
And just change the pattern ('^(DIV|IMG)$') to suite your needs.
If you can use jQuery, try
var child = $("#theul" + id).find("div,img");
Otherwise, see JavaScript NodeList.

Categories

Resources