problems with Array.prototype.indexOf.call - javascript

If i click the a element "Link1" e.target in the function is the node Link1. I want to know in what index this node is in the ul children in this case i want indexOf to return 0 because Link1 is on position 0, and i i click 2 i want it to be 1.
HTML
<div class="link">
<ul>
<li><a>Link1</a></li>
<li><a>Link2</a></li>
</ul>
</div>
JAVASCRIPT
self.query('.link').forEach(function(linkNode, flikIndex, flikArr) {
dojo.query(linkNode, 'click', function(e) {
var t = e.target; //If i click Link1 this is Link1 and if i click Link2 and so on.
var parent = t.parentNode; //Contains the parent to my a in this case li
var ancestor = t.parentNode.parentNode.childNodes; //Containes 2 li
var index = Array.prototype.indexOf.call(parent, ancestor); //Return -1 but i want it to return 0 because Link1 is on place [0] in the array.
}
}
Please help me get the right index

var index = Array.prototype.indexOf.call(parent, ancestor);
// ^ Array ^ Element in the array
So you want this:
var index = Array.prototype.indexOf.call(ancestor, parent);
Since ancestor is the element ("array") that contains parent.

Try this:
let nodes = Array.from( parent.closest('ul').children);
let index = nodes.indexOf(li);
When we work with a NodeList, getting the index of the li can be tricky using this approach:
var ancestor = t.parentNode.parentNode.childNodes;
var index = Array.prototype.indexOf.call(ancestor, parent);
If we have text in the lis, then these are also considered childNodes, and so the index of the li which is returned will be its index in the nodeList which consists of other children such as text, and not merely other lis. Therefore, you may not be getting the desired result in case you are only interested in the position of an li relative to the other lis in the ul

Related

How to get index, position number of element with certain class with jQuery

I have this markup
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
My question is: how to get "index" number of element with class two. I'm not asking of regular index number of element in parent div. I need to know that when i'm clicking at first element with class one that next two element have 0 index or it's first element in this list with class two, and so on.
I've tried with index() method and eq() and always i have the real index number of this element in parent div. I hope this is clear, thx for help.
You need to find the elements index in collection of element with sameclass:
$('.parent > div').click(function(){
var index;
if($(this).is('.one'))
index = $('.parent > .one').index(this);
else
index = $('.parent > .two').index(this);
});
This should be the faster way to get the index you are looking for.
Instead of retrieving all matches, it just counts the number of elements of the same class among previous leafs in your DOM.
Also, it allows having multiple <div class="parent"> and still work
$('.parent div').click(function() {
// Retrieve clicked element class (one, two)
var elClass = $(this).attr('class');
// Retrieve all previous elements that have the same class
// and count them
var prevElmts = $(this).prevAll('.' + elClass),
numPrevElements = prevElmts.length;
console.log(numPrevElements);
})
Using jquery you can find index of element which have same class name or tag name
$(".class_name").on("event_name", function() {
var index=($(this).index());
console.log('index : ',index);
});
This may work for you.
var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);

How to find number of <ul> inside each div

I have a large file of this form [similar div's throughout]. I want to be able to select a div, find the number of ul's in it and traverse through each of them to get value of each li in it.
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
I have tried looping through all experiment divs, then select the uls, but it selects all the ul in the page, not only the ones under current div.
$('experiment ul').eq('$i');
Your HTML is currently incorrect, since you're simply starting new <div> and <ul> elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.
You need to select all of the <div class="experiment"> elements, then iterate through them. To do that you can use the .each() function. It might look something like this:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
Take a look at this jsFiddle demo.
to get all the ul inside div.experiment
var ul = $('.experiment').find('ul');
and to get all li elements inside each ul found above
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
First of all you need to work out the correct selector for each DIV.
The selector you want is:
".experiment"
Notice the . to denote a class selector.
This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
IMPORTANT: There is also an error with your HTML, you need to close your <ul> elements correctly using </ul>

finding the index of an element in relation to a specific parent

Looking at the example here - http://jsfiddle.net/uqYeQ/3/
The first row behaves as expected, returning the index of the div within it's parent.
I'd like the 2nd row to behave in the same way, I'd like it to return between 0 and 4 depending on which div has been clicked. I'd like to know the index of the div that has been clicked in relation to it's parent list item.
I cannot change the html at all.
Give this a whirl (fiddle)
$("li > .myclass, li > .container").click(function(e){
$("#result").html($(this).index());
});
​
This worked for me (fiddle)
$('.myclass').click(function(){
var theIndex = $(this).index();
$('#result').html(theIndex);
})
$('.container').click(function(){
var theIndex = $(this).index();
$('#result').html(theIndex);
})
but antisanity's is sexier.
The following is one approach
$('.myclass').click(function() {
var liElem = $(this).parents('li')[0]; // get li element who is a parent of the clicked element
var elems = $(this).parents();
elems.push($(this)); //array contains all parents of the clicked element and the clicked element
$(elems).each(function(key, elem) {
if ($(elem).parent()[0] == $(liElem)[0]) {
$('#result').html($(elem).index());
}
});
})
jsFiddle

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

Categories

Resources