Get list item index in HTML ul list using Javascript - javascript

I have the following HTML page:
<html>
<head>
<script type="text/javascript" src="JavaScript/Menu.js"></script>
</head>
<body>
<ul>
<li><a onclick="GetIndex(this)">One</a></li>
<li><a onclick="GetIndex(this)">Two</a></li>
<li><a onclick="GetIndex(this)">Three</a></li>
<li><a onclick="GetIndex(this)">Four</a></li>
</ul>
</body>
</html>
And the Menu.js javascript:
function GetIndex(sender)
{
var aElements = sender.parentNode.parentNode.getElementsByTagName("a");
var aElementsLength = aElements.length;
var index;
for (var i = 0; i < aElementsLength; i++)
{
if (aElements[i] == sender) //this condition is never true
{
index = i;
return index;
}
}
}
Why is the commented condition never met? How do I compare if the two HTML elements are equal in Javascript? Thanks for all the help.

"Your code is correct"

Old Post, but here is a quick function to do this:
function nodeIndex(el) {
var i=0;
while(el.previousElementSibling ) {
el=el.previousElementSibling;
i++;
}
return i;
}
This should work with an element reference as the parameter. It basically just returns the number of previous siblings.

try to use:
if (aElements[i] === sender)
instead of
if (aElements[i] == sender)

Are you sure GetIndex function gets executed on click event on anchor tag?
Try by giving href attribute to anchor tag. You can write either
One
or
One
here is the working example http://jsfiddle.net/QfRSb/

Jquery can help using prevAll()
$(document).on("click","li",function(){
var index=$(this).prevAll();
alert(index);
});

The modern way to find index of element
[...el.parentNode.children].indexOf(el)

Related

How to delete specified children?

<body>
<p>dfg</p>
<h1>yoyo</h1>
<h1>yoyo2</h1>
<ul>
<li>somo</li>
</ul>
</body>
For example I want to delete only h1 from body. The other children should stay
You can use a CSS selector.
You can do it using jQuery or VanillaJS. For instance, here is my code for VanillaJS.
var headers = document.querySelectorAll('h1');
headers.forEach(function(h) { h.remove(); });
This will effectively remove the headers from the DOM.
We can create our own fn to remove node by tag for usability. please review this one:
function rem(tag) {
var h = document.querySelectorAll(tag); //return NodeList not array
[].forEach.call(h,function(elm) {
elm.parentNode.removeChild(elm);
});
}
//passing tag to remove
rem('p');
<body>
<p>dfg</p>
<h1>yoyo</h1>
<h1>yoyo2</h1>
<ul>
<li>somo</li>
</ul>
</body>
You can use getElementsByTagName to get an HTMLCollection (not an array) of the h1 tags, which is live.
When an element is removed, the elements update their indexes accordingly which means that you have to remove each element from the last position to the first.
Javascript solution:
var h1Elems = document.getElementsByTagName('h1');
for(var i = h1Elems.length - 1; i >= 0; i--){
h1Elems[i].parentElement.removeChild(h1Elems[i]);
}
See this code working in this jsfiddle

a href - how to execute javascript and jump to a section?

Is it possible to make <a href=""> to do 2 things? One to javascript: and the other to jump to a section in a documents using <a id=""> and a # mark.
In short I am looking for something like this:
Link
Yes, use onclick property:
Link
Of course, you can do this:
Link
I'd suggest using unobtrusive JavaScript, moving the event-handling away from your HTML:
function doSomething(){
console.log("You clicked on the " + this.tagName.toLowerCase() + " element.");
}
var link = document.getElementById('aElementID');
link.onclick = doSomething;
JS Fiddle demo.
This does, though, require an id on the a element:
Go to the paragraph
You could, though, use a class-name instead, though this involves binding the functionality to multiple elements, with a for loop (or similar); given the a elements having the form:
Go to the paragraph
Go to the other paragraph
The JavaScript would become:
function doSomething(){
console.log("You clicked on the " + this.tagName.toLowerCase() + " element.");
}
var links = document.getElementsByClassName('linkClassName');
for (var i = 0, len = links.length; i < len; i++){
links[i].onclick = doSomething;
}
JS Fiddle demo.
You could even bind the event-handling to an ancestor element, and basing the response on which element received the event; this would allow HTML of the form:
<div id="arbitraryAncestorElement">
Go to One
<ul>
<li>Go to Two</li>
<li>Go to Three</li>
</ul>
</div>
With the JavaScript:
function doSomething(event){
if (event.target.tagName.toLowerCase() === 'a') {
console.log("You clicked on an 'a' element.");
}
}
var ancestor = document.getElementById('arbitraryAncestorElement');
ancestor.onclick = doSomething;
JS Fiddle demo.

Javascript efficient approach for changing inner dom elements of a list item

I have a unordered list with 12 list items inside it
<ul class="rb-grid" id="list">
<li class="view view-fifth">
<div class="mask">
<h2>Article Name</h2>
<p>Brief</p>
Read More
</div>
</li>
...
...
</ul>
Now what i want is that on page load i have to change the content of these h2 and p tags, now while i can do this by hardcoding every list item, but can anyone tell me a better way to make all changes at once by using javascript or jquery anything....
Now i found something like this in dojo , this will make clear what i want actually -
var items = registry.byId("list").getChildren();
array.forEach(items, function(item, idx) {
item.onClick = function(evt) {
};
});
I want to do some such thing to change the contents of the h2 and the p tags inside every list items
Try this: (jquery)
var lis = $('.rb-grid').children('li');
for(var i = 0; i < lis.length : i++){
$(lis).eq(i).find('p').html("change to something");
$(lis).eq(i).find('h2').html("change to something");
}
js
var x =$('.rb-grid').children('li');
x.find('p').html('change to something');
x.find('h2').html('change to something');
A non jquery way:
var ee = document.getElementById('list').getElementsByTagName('li');
for(i=0; i<ee.length; i++) {
ee[i].getElementsByTagName('h2')[0].textContent = "hello world";
ee[i].getElementsByTagName('p')[0].textContent = "article 2";
}
EDIT: It seems IE previous to IE9 does not have textContent and should use innerText instead. Thanks Mr_Green!
Here for comparison is a more idiomatic jQuery version of Mr_Green's answer:
$('.rb-grid').children('li').each( function( i, element ) {
var $element = $(element);
$element.find('p').html("change to something");
$element.find('h2').html("change to something");
});
OTOH, you may not even need the loop, depending on what you're doing. If you just want to change all the relevant nested p and h2 elements to the same value, then Tushar Gupta's answer is a simpler way to do it.

How can access bunch of <li>?

I have a list of texts and I want to change their innerHTML. how can I do that by javascript if I have thousands of li tag (whose data come from database)?
<div>
<ul>
<li>a</li>
<li>as</li>
<li>asd</li>
<li>asds</li>
<li>asdsa</li>
<li>asdsad</li>
<li>asdsadz</li>
<li>asdsadzc</li>
....
.....
</ul>
</div>
-Thanks.
Update
JS code being used:
function a(){
var parent = document.getElementById("z");
var i = 0;
for(i = 0; i <= parent.children.length; i++){
if(parent.children[i].tagName == "LI"){
if(i%2!=0){
parent.children[i].innerHTML="ok";
}
}
}
}
document.onload=a(); // this didn't work. so I called the function in body tag instead of that.
<body onload="a();">
Have you tried using getElementsByTagName ? Sonds like it would help you find the elements you're trying to work with.
Edit
If you can give an Id to the UL element that holds the li's you're trying to process, you could do something like this:
var parent = document.getElementById("yourID");
var i = 0;
for(i = 0; i < parent.children.length; i++){
if(parent.children[i].tagName == "LI") {
//do what you want...
}
}
EDit 2
You have to change the last line on your script:
document.onload=a();
With this one: window.onload=a;
That'll get your function to execute on the onLoad event. Note that there might be some crossbrowser incompatibility, I would suggest researching a bit on how to execute functions on the onload event on a crossbrowser manner, or just adding this to your body tag:
<body onload="a();">
Given the - not so far fetched - precondition you wish to use jQuery, you can select them and iterate over them with "each".
$("li").each(
function() { $(this).html("changed content"); }
);
If you are not using jQuery, using a js-library that helps you out with the quircky dom is probably not a bad idea...
The general idea
Select nodes
Iterate and change html
is always the same.

How to get value inside td using Dom

<html>
<head>
</head>
<body>
<div id="content_Data"></div>
<script type="text/javascript">
function auto()
{
alert("auto called");
document.getElementById('content_Data').innerHTML='<div><table><tr><td>10</td><td>20</td></tr></table></div>';
alert(document.getElementById('content_Data').innerHTML);
getelements();
}
function getelements(){
var searchElement=document.getElementById('content_Data').getElementsByTagName("div");
for( var i=0; i<searchElement.length; i++ )
{
var child_length=searchElement[i].childNodes.length;
for( j=0; j<child_length; j++ )
{
alert(searchElement[i].childNodes[j].nodeValue);
}
}
}
</script>
<script>auto();</script>
</body>
</html>
try looking at innerHTML of td node. Or if you want only text, then it is innerText for IE and textContent for others.
alert(searchElement[i].childNodes[j].innerHTML)
also, jQuery will greatly simplify your code.
Well, just navigate there. For example
document.getElementById('content_Data').firstChild.firstChild.firstChild
gets you the first table cell (with value 10).
You can change the getElementsByTagName("div") to get the td elements:
var searchElement=document.getElementById('content_Data').getElementsByTagName("td");
And, it's better to declare the j variable on the second for :D. That's all you need to change

Categories

Resources