How to get the position of last child in a element, I mean the number (the index)?
I want the code below to alert "4", since there is four elements.
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="container">
<div id="div1">div1</div>
<div id="div2">div2
<div id="child_div1">div2</div>
<div id="child_div2">div2</div>
</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
</div>
<script>
var container = document.getElementById('container'),
last_child_of_container = container.childNodes.length;
alert('position of last div is'+ last_child_of_container);
</script>
</body>
</html>
try
document.getElementById('container').children.length
http://jsfiddle.net/pxfunc/MGnCG/
This works :-)
var container = document.getElementById('container');
var count = 0;
var length = container.childNodes.length;
for (var i = 0; i < length; i++) {
if (container.childNodes[i].tagName &&
container.childNodes[i].tagName == 'DIV') {
count += 1;
}
}
alert(count);
Give document.getElementById('container').childElementCount a go
Here you go: http://jsfiddle.net/2t3VJ/
var container = document.getElementById('container'), children = 0;
for( var i=0, c = container.childNodes, l = c.length ; i < l; i++ ) {
if( c[i].nodeType == 1 ) { // if this is a HTMLSomeELement :)
children++;
}
}
alert( children );
Add h at the end of container.childNodes.lengt
container.childNodes.length;
See jsFiddle
For immediate child use childElementCount
container.childElementCount;
var container = window.document.getElementById("container");
var child_nodes = container.childNodes;
var child_nodes_length = child_nodes.length;
var count = 0;
var node;
var i;
for (i = 0; i < child_nodes_length; i++) {
node = child_nodes.item(i);
if (node.nodeType === 1) {
++count;
}
}
window.alert(count);
For people who wants any element (e.g. not necessarily the last one)
var wanted = document.getElementById('wanted');
var index = [].indexOf.call(wanted.parentElement.children, wanted);
Its very easy to get the position of the last element ... people are making it so complicated... try my code
function getLastElPos(container) {
return container.childNodes.length;
}
it returns the length of the child nodes in the container element, and the length means the last element (lol).
you can use it like this:
var container = document.getElementById('container');
var lastElement = getLastElPos( container );
alert( lastElement );
it works fine in all browser :)
Related
I have an HTML like this
How add ID to HTML href with javascript
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<script>
var els = document.getElementsByClassName("tab");
// loops els
for(var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function(){
x = document.querySelector(".tab> a")
// do something
x.id = "expid";
}
}
</script>
I want to add the id to each tag when I click this. Pls help me. Thks so much
<div class="tabs">
... your html code.
</div>
const tabs = document.querySelector('.tabs')
tabs.addEventListener('click', event => {
const aTag = event.target
if (aTag.tagName !== 'A') return
aTag.id = `EXPID#${getIndexIn(aTag, tabs)}`
})
function getIndexIn(element, parent): number
What's the meaning to be it?
Your call to document.querySelector() always returns the first .tab > a link in the document. You can this.querySelector() to return the link in the DIV that you clicked on instead.
I've changed the code to use a class rather than ID, since you shouldn't have duplicate IDs.
Loop through all the DIVs. If it's the DIV that the user clicked on, add the class, otherwise remove it.
var els = document.getElementsByClassName("tab");
// loops els
for (var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function() {
for (var j = 0; j < els.length; j++) {
x = els[j].querySelector("a");
if (els[j] == this) {
x.classList.add("expid");
} else {
x.classList.remove("expid");
}
}
}
}
.expid {
background-color: yellow;
}
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
const anchors = document.getElementsByTagName('a');
const ids= [1,2,3,4,5];
let index =0 ;
for(let a of anchors ){
a.href=ids[index++]
}
you can try this way it's a cool and easiest what I do with pure js
Why is card element not duplicated 4 times?
function generate4Cards() {
for (var i=0; i < 4; i++) {
var card = document.getElementById('card');
document.body.appendChild(card);
}
}
<body onload="generate4Cards()">
<div id="card">I am a card</div>
</body>
When you call appendChild with an existing element, that element will be removed from its former position in the DOM and appended to the new container. You'll have to explicitly create the div on each iteration instead.
But, having duplicate IDs in a single document is invalid HTML, so probably best to remove the id (or use a class instead):
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.body.appendChild(card);
}
Another option is to use cloneNode:
var originalCard = document.querySelector('div');
for (var i = 0; i < 4; i++) {
var card = originalCard.cloneNode(true);
document.body.appendChild(card);
}
<div>I am a card</div>
foo.append(bar) puts bar at the end of foo.
If I put my car at the end of my road, and then put my car at the end of my drive then I don't have two cars.
append only puts bar where you tell it to put it.
It doesn't duplicate it because it isn't supposed to.
Here is the sample code you are looking for -
<html>
<head>
<script>
function generate4Cards() {
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.getElementById('cardHolder').appendChild(card);
}
}
</script>
</head>
<body onload="generate4Cards()>
<div id="cardHolder"></div>
</body>
</html>
I'm trying to make my dynamically added divs draggable but if I call after
$("#draggable").draggable({});
this
for( var i = 0; i < 5; i++ ){
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
}
there is no chance to make divs draggable.
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem.
Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/
Thank you in advice.
You will have to initialize draggable widget after appending new element.
Try this fiddle:
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.backgroundColor = 'blue';
document.body.appendChild(smallone);
$(smallone).draggable({});
}
Use a class instead of id as id must be unique
$(".draggable").draggable({});
Assign draggable class to all divs
simple 1 ...
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
$(".smallDiv").draggable({});
}
it is working... http://jsfiddle.net/9jstfwpm/7/
I made a code that should highlight searched string but it is not working.
Here is the code:
<body>
<div>div is here</div>
<div id="divid">
<div>this is a div 1</div>
<div> this is a div 2</div>
<div> this is a div3</div>
</div>
<div> another div is here</div>
</body>
Here is a javascript code.
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var div = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i <= div.length; i++){
var div1 = div[i].innerHTML;
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>");
div1.innerHTML = rword;
}
}
There are begginer mistakes in your code. Let me correct them:
function checkit(){
var hlWord = "div"; //Define string that will be emphasized by <b> tag
var nregex = new RegExp(hlWord,"gi");//Create global, case-insensitive regexp
var div = document.getElementById("divid").getElementsByTagName('div'); //Get element collection of divs in div#divid
for(var i=0; i < div.length; i++){ //Loop through my element collection
var div1 = div[i].innerHTML; //Get the innerHTML of on of the divs
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>"); //Surround my string with <b>
div[i].innerHTML = rword; //Change the innerHTML back
}
}
You used this for condition: i<=div.length. This is wrong. Do not forget, that we count from 0 so: [0, 1, 2, 3].length = 4. Last element for such array has index 3. The [] is an array literal.
By mistake, you assigned div1.innerHTML. div1 was a string. The element you want to change is div[i].
I made a JSFiddle too!
The problem with you code will be, amongst other problems, that nested div elements will be broken. You should use some kind of recursion if you want to highlight the word 'div'.
Here is such a function:
function highLight(term,root){
var allDiv = root.querySelectorAll('div'),
replacer = function(a){return '<span class="highlight">'+a+'</span>'};
for (var i=0; i<allDiv.length; i+=1){
if (allDiv[i].querySelectorAll('div').length){
highLight(term, allDiv[i]);
} else {
var re = RegExp('('+term+')','gi');
allDiv[i].innerHTML = allDiv[i].innerHTML.replace(re,replacer);
}
}
}
And here is a jsfiddle to play around with it
A more advanced jsfiddle
You have several errors: there you go:
http://jsfiddle.net/55U6j/1/
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var divs = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i < divs.length; i++){
var div = divs[i];
var html = div.innerHTML;
var rword = html.replace(nregex,"<b>"+hlWord+"</b>");
div.innerHTML = rword;
}
}
I am trying dynamically add children DIV under a DIV with ID="prnt". Addition of nodes work fine no problem. However strange enough when it comes to deleted nodes its only deleting the even numbered nodes including 0. Why is this, I could be something stupid but it seem more like a bug. I could be very wrong.
<script type="text/javascript">
function displayNodes()
{
var prnt = document.getElementById("prnt");
var chlds = prnt.childNodes;
var cont = document.getElementById("content");
for(i = 0; i < chlds.length; i++)
{
if(chlds[i].nodeType == 1)
{
cont.innerHTML +="<br />";
cont.innerHTML +="Node # " + (i+1);
cont.innerHTML +="<br />";
cont.innerHTML +=chlds[i].nodeName;
cont.innerHTML +="<br />";
}
}
}
function deleteENodes()
{
var prnt = document.getElementById("prnt");
var chlds = prnt.childNodes;
for(i = 0; i < chlds.length; i++)
{
if(!(chlds[i].nodeType == 3))
{
prnt.removeChild(chlds[i]);
}
}
}
function AddENodes()
{
var prnt = document.getElementById("prnt");
//Only even nodes are deletable PROBLEM
for(i = 0; i < 10; i++)
{
var newDIV = document.createElement('div');
newDIV.setAttribute("id", "c"+(i));
var text = document.createTextNode("New Inserted Child "+(i));
newDIV.appendChild(text);
prnt.appendChild(newDIV);
}
}
</script>
<title>Checking Div Nodes</title>
</head>
<body>
<div id="prnt">
Parent 1
</div>
<br />
<br />
<br />
<button type="button" onclick="displayNodes()">Show Node Info</button>
<button type="button" onclick="deleteENodes()">Remove All Element Nodes Under Parent 1</button>
<button type="button" onclick="AddENodes()">Add 5 New DIV Nodes</button>
<div id="content">
</div>
</body>
The problem is you're modifying the collection as you loop through it. Iterating in reverse should fix this...
for(i = chlds.length-1; i >= 0; i--)
{
if(!(chlds[i].nodeType == 3))
{
prnt.removeChild(chlds[i]);
}
}
Do away with the if(!(chlds[i].nodeType == 3)) nodeType check.
You can pull only the divs by doing a .querySelectorAll('div')
function deleteENodes()
{
var chlds = document.getElementById("prnt").querySelectorAll('div');<----
for(i = 0; i < chlds.length; i++)
{
if(!(chlds[i].nodeType == 3))
{
prnt.removeChild(chlds[i]);
}
}
}
The problem is as you're deleting nodes (starting from the beginning), the index of the remaining child nodes is decreasing by one each time:
Given 5 children:
Child1 Index0
Child2 Index1
Child3 Index2
Child4 Index3
Child5 Index4
When you go to remove them, this is what is happening
.removeChild(0) removes Child1
Child2 is now Index0
Child3 is now Index1
....
next Iteration:
.removeChild(1) removes Child3
Child2 is still Index0
Child4 is now Index1
Child5 is now Index2
....
Solution. Remove children from last index and move towards 0.
The NodeList returned by childNodes is "live" - removing a child updates the list immediately.
What's happening is that you're removing an element, which decreases the length of the list by 1, causing your loop to skip an element.
One way to avoid this is by copying the elements into anArray.
E.g.
var nodes = [];
for (var i = 0; i < chlds.length; i++) {
nodes.push(chlds[i]);
}
for(i = 0; i < nodes.length; i++)
{
if(!(nodes[i].nodeType == 3))
{
prnt.removeChild(nodes[i]);
}
}