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

<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>

Related

Append div multiple times using JavaScript on DOM Loaded [duplicate]

This question already has an answer here:
Append Div with Multiple Child Divs Using For Loop
(1 answer)
Closed 1 year ago.
I want to append the HTML child_element div multiple times as defined on variables inside the parent_element using Javascript on DOM Load.
Desire Output:
<div class="parent_element">
<div class = "child_element">
<div class = "child_element">
<div class = "child_element">
<div class = "child_element">
<div class = "child_element">
</div>
You can create a child node object and append it to the parent node in loop. Since you have multiple child nodes to be appended you can use DocumentFragment
const parentNode = document.createElement('div');
parentNode.classList.add('parent_element');
const childNode = document.createElement('div');
childNode.classList.add('child_element');
const fragment = new DocumentFragment();
for(let i=0; i<[*no_of_times_you_want_child_node*]; i++) {
fragment.appendChild(childNode.cloneNode(true));
}
// finally append dom fragment to parent
parentNode.appendChild(fragment);
Assuming that you want the number of children to be defined by an attribute "variables inside the parent_element"
<div class="parent" children="5"></div>
<script>
const parentEl = document.querySelector(".parent");
const numOfChildren = +parentEl.getAttribute("children");
const fragment = new DocumentFragment();
for (let i=0; i<numOfChildren; i++) {
const childEl = document.createElement("div");
childEl.classList.add("child");
fragment.appendChild(childEl);
}
parentEl.append(fragment);
</script>
The basic process is:
Get a reference to the parent element using the class selector
Retrieve the number of children you want from the attribute named children. This is a string value so the + will convert it to a number
Loop through the creation of a new element on the DOM adding the desired class name before appending the child.
Edit: As per pilchard's suggestion I've merged in DocumentFragment from abhishek khandait's answer.
You can dynamically add a new div element using jquery.
<script>
function addNewDivElement() {
$("#parent_element").append('<div class = "child_element">')
}
</script>
the function addNewDivElement can be called on click of a button. something like below:
<button onclick="addNewDivElement()">
Add
</button>

Get all tag nodes inside another tag recursively

I have an html document consists of a <div id = "main">. Inside this div may be several levels of nodes, without a precise structure because is the user who creates the document content.
I wanto use a JavaScript function that returns all nodes within div id = "main". Any tag is, taking into account that there may be different levels of children.
For now I have this function that returns all tags, even those outside to div id = "main":
function getNodes() {
var all = document.getElementsByTagName("*");
for (var elem = 0; elem < all.length; elem++) {
//do something..
}
}
As such this document:
<div id="main">
<h1>bla bla</h1>
<p>
<b>text text text </b> text text <i>text</i>.
<img src=".."></img>
</p>
<div>
<p></p>
<p></p>
</div>
<p>..</p>
</div>
The function getNodes would return an array of object nodes (I don't know how to represent it, so I list them):
[h1, p, b, i, img, div, p, p, p]
Thank you
Use document.querySelectorAll. It returns a NodeList, not an array, but you can loop over it in the same way:
function getNodes() {
var all = document.querySelectorAll("#main *");
for (var elem = 0; elem < all.length; elem++) {
//do something..
}
}
http://jsfiddle.net/suuja4L5/
Just get the parent element and then get the descendents just as you did:
var mainDiv = document.getElementById("main");
mainDiv.getElementsByTagName("*")
if you want all child of <div id="main">,then use the following :
var children = document.querySelector("#main").children;

How can I get an element's attribute from the parent's parent element's ID using JavaScript?

So I have the following HTML...
HTML:
<div id="col1">
<img src="1.jpg">
</div>
And I am implementing a HTML5 drag and drop feature where the inner html of col1 is changed for the dragged element's inner html - so basically the columns change their content.
I have another div (let's call that swap-text) where I want to change its text content depending on what image is presently inside col1.
This is why I want to figure out how I can obtain col1's img element's src attribute value through JavaScript so I can then write an if statement to change the content of the swap-text depending on which image is in col1.
I could add ID's to the img elements but then I still don't know how I would write the condition to check if say, img-id1 parent is col1.
Attempt(s):
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
for (var i = 0; i < doc.childNodes.length; i++) {
children = doc.childNodes[i];
console.log(children);
}
//document.getElementById("img")
//children[1].getAttribute('src'); - cannot call method 'getAttribute' of undefined
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);
This work fine pure javascript:
document.getElementById("col1").getElementsByTagName("img")[0].getAttribute("src");
var doc = document.getElementById("col1");
var img = document.getElementsByTagName('img')[0];
var imgParent = img.parentElement;
This is how you determine the elements parent/
I suggest you to use JQuery so you can simply use:
$("img").attr("id"); //Return the id of the img element
Check this:
var column = document.getElementById("col1");
var imgSrc = column.getElementsByTagName("img")[0].getAttribute("src");
Or just use the jQuery - it's simpler:
$('#col1 img').attr('src');
as you will only have one child node in col1 (the img), change the for loop.
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
//for (var i = 0; i < doc.childNodes.length; i++) {
// children = doc.childNodes[i];
// console.log(children);
//}
childen = doc.childNodes[0];
// or children = doc.firstChild;
console.log(children);
//document.getElementById("img")
console.log(children.getAttribute('src')); - children is single object
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);

Count how many elements in a div

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>

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] );

Categories

Resources