Problem accessing div elements - javascript

<div id="nav">
<ul id="linkselect">
<li class="important" >Home</li>
<li><a href="rlsdoc.html" >Release Document</a></li>
<li>Data Dump</li>
<li>Facility Setup</li>
<li>DBU Elimination</li>
<li>Contact us</li>
</ul>
</div>
I want to put all the links (Home, Release Document etc) of div "nav" into a array so that I can iteratively use them. Please help me with the JavaScript code for this. Thanks in advance.

document.getElementById("nav").getElementsByTagName("a")
this will return a node list that contains all "a" nodes

This should do what you need with pure JavaScript:
window.onload = function() {
var data = [];
var oDiv = document.getElementById("nav");
var links = oDiv.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
data.push(links[i].innerHTML);
alert(data.join("\n"));
};
Live test case.

We could use a combination of .querySelectorAll() to query the desired anchors and Array.prototype.forEach to iterate over those static element references.
var anchors = document.querySelectorAll('#linkselect a'),
each = [].forEach;
each.call( anchors, function( a ) {
console.log( a );
});
Note: Both methods are not available in "old'ish" browsers, but are easily to create, lots of shims available.

Try this.
Javascript
var items = [];
var anchors = document.getElementById("nav").getElementsByTagName("a");
for(var i = 0; i<anchors.length; i++){
items.push(this.href);
}
jQuery
var items = [];
$("#nav a").each(function(){
items.push(this.href);
});

jQuery:
$('#linkselect li a')
plain javascript:
document.getElementById('linkselect').getElementsByTagName("a")

Related

How can I properly convert the following Jquery to pure Javascript?

How can I convert the Jquery below to pure JavaScript?
var $buttons = jQuery("#thePaginator li a");
for (var index = 0; index < $buttons.length; index++) {
var $button = $buttons.eq(index);
$button.click(function() {
var newPage = $(this).data("page");
jQuery("#attribute-myAttribute").val(newPage);
jQuery("#update").click();
});
}
I wouldn't normally ask a question like this, but the conversion has been difficult, especially with the event listener. Here is what I have so far:
runPaginate();
function runPaginate(){
var buttonArray = document.getElementById("paginator_TCC").querySelectorAll('li');
for(i=0;i<(buttonArray.length);i++){
buttonArray[i].addEventListener('click', runUpdate);
}
}
function runUpdate(){
console.log("runUpdate started")
// will need to add code in here for update
}
update (in Jquery) is a method that is called to update attributes on the page. Consider the runUpdate function to suffice for that method call.
I believe that I'm having so much trouble because I'm dealing with HTML Collection, so when I get the li elements (which are actually buttons) I can't seem to add an event listener to them. Below is the inspection result from Dev Tools:
<div id="thePaginator" class="simple-pagination">
<ul>
<li class="disabled">
<span class="current prev">Prev</span>
</li>
<li class="active">
<span class="current">Year 1</span>
</li>
<li class="disabled">
<span class="current next">Next</span>
</li>
</ul>
</div>
Any assistance is appreciated.
I'd use a for...of loop, and move the callback into the loop. That way you can access the iterator:
for(const button of buttonArray){
button.addEventListener('click', function runUpdate() {
const { data } = button.dataset;
//...
});
}
This is the JS equivalent of your jQuery (this just replaces the jQuery method calls with their equivalent JS method calls)
var buttons = document.querySelectorAll('#thePaginator li a');
for(var index = 0; index < $buttons.length; index++) {
var button = buttons[index];
button.addEventListener("click", function(evt) {
var newPage = this.dataset.page;
document.getElementById('attribute-myAttribute').value = newPage;
document.getElementById('update').click();
})
}

How to do a DOM sort of a UL with TypeScript in Angular2+ (without using ngFor)? [duplicate]

I have a set of three list items that I would like to automatically display from high to low on page load. Ideally using jquery or javascript.
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
Each list item needs its own ID because they each have individual background images. The numbers must text nodes so that a user can edit them.
This will probably be the fastest way to do it, since it doesn't use jQuery:
function sortList(ul){
var new_ul = ul.cloneNode(false);
// Add all lis to an array
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
// Sort the lis in descending order
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) -
parseInt(a.childNodes[0].data , 10);
});
// Add them into the ul in order
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
Call the function like:
sortList(document.getElementsByClassName('list')[0]);
You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.
Example JSFiddle
Edit
Since you mentioned that you want it to happen on pageLoad, I'm assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList to the head of your page and use it immediately after your list like this:
<head>
...
<script type="text/javascript">
function sortList(ul){
var new_ul = ul.cloneNode(false);
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) - parseInt(a.childNodes[0].data , 10);
});
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
</script>
</head>
<body>
...
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
<script type="text/javascript">
!function(){
var uls = document.getElementsByTagName('ul');
sortList( uls[uls.length - 1] );
}();
</script>
...
</body>
You can try this
var ul = $(".list:first");
var arr = $.makeArray(ul.children("li"));
arr.sort(function(a, b) {
var textA = +$(a).text();
var textB = +$(b).text();
if (textA < textB) return -1;
if (textA > textB) return 1;
return 0;
});
ul.empty();
$.each(arr, function() {
ul.append(this);
});
Live example : http://jsfiddle.net/B7hdx/1
you can use this lightweight jquery plugin List.js cause
it's lightweight [only 3K script]
easy to implement in your existing HTML table using class
searchable, sortable and filterable
HTML
<div id="my-list">
<ul class="list">
<li>
<h3 class="name">Luke</h3>
</li>
<li>
<h3 class="name">John</h3>
</li>
</ul>
</div>
Javascript
var options = {
valueNames: ['name']
};
var myList = new List('my-list', options);
There's also this small jQuery plugin. Which would make your sort nothing more than:
$('.list>li').tsort({attr:'id'});
This code will sort that list assuming there is only one .list item:
function sortList(selector) {
var parent$ = $(selector);
parent$.find("li").detach().sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
parent$.append(el);
});
}
sortList(".list");
You can see it work here: http://jsfiddle.net/jfriend00/FjuMB/
To explain how it works:
It gets the .list parent object.
It finds all the <li> child objects.
It removes all the <li> child objects from the DOM, but preserves their data
It sorts the li objects using a custom sort function
The custom sort function gets the HTML in the li tag and converts it to a number
Then, traversing the array in the newly sorted order, each li tag is appended back onto the original parent.
The result is that they are displayed in sorted order.
Edit:
This improved version will even sort multiple list objects at once:
function sortList(selector) {
$(selector).find("li").sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
$(el).parent().append(el);
});
}
sortList(".list");
Demo: http://jsfiddle.net/jfriend00/RsLwX/
Non jquery version (vanilla javascript)
Benefits: the list is sorted in place, which doesn't destroy the LI's nor remove any events that may be associated with them. It just shuffles things around
Added an id to the UL:
<ul id="myList" class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
and the vanilla javascript (no jquery)
// Grab a reference to the UL
var container = document.getElementById("myList");
// Gather all the LI's from the container
var contents = container.querySelectorAll("li");
// The querySelector doesn't return a traditional array
// that we can sort, so we'll need to convert the contents
// to a normal array.
var list = [];
for(var i=0; i<contents.length; i++){
list.push(contents[i]);
}
// Sort based on innerHTML (sorts "in place")
list.sort(function(a, b){
var aa = parseInt(a.innerHTML);
var bb = parseInt(b.innerHTML);
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});
// We'll reverse the array because our shuffle runs backwards
list.reverse();
// Shuffle the order based on the order of our list array.
for(var i=0; i<list.length; i++){
console.log(list[i].innerHTML);
container.insertBefore(list[i], container.firstChild);
}
And the fiddle proof: https://jsfiddle.net/L27gpnh6/1/
You can use this method:
var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
Check the article here:
http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
Edit: There is a very cool jquery plugin that does that : http://tinysort.sjeiti.com/
Something like this should help:
var $parent = $(".list");
$(".list li").sort(function (a, b) {
return window.parseInt($(a).text(), 10) - window.parseInt($(b).text(), 10);
}).remove().each(function () {
$parent.append($(this));
});
One method could be to sort an array (well, a jQuery object) of the li elements and replace the contents (using the html method) of the ul with the sorted array of elements:
$(".list").html($(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}));
Here's a working example.
using jQuery for help:
var sortFunction = function(a, b) {
return (+($(b).text())) - (+($(a).text()));
}
var lis = $('ul.list li');
lis = Array.prototype.sort.call(lis, sortFunction);
for (var i = 0; i < lis.length; i++) {
$('ul.list').append(lis[i]);
}
Fiddle Link
Sort jQuery collection as usual array and then append each element back in correct order.
$(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}).appendTo('.list');
http://jsfiddle.net/zMmWj/

Sort an html list with javascript

I have a set of three list items that I would like to automatically display from high to low on page load. Ideally using jquery or javascript.
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
Each list item needs its own ID because they each have individual background images. The numbers must text nodes so that a user can edit them.
This will probably be the fastest way to do it, since it doesn't use jQuery:
function sortList(ul){
var new_ul = ul.cloneNode(false);
// Add all lis to an array
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
// Sort the lis in descending order
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) -
parseInt(a.childNodes[0].data , 10);
});
// Add them into the ul in order
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
Call the function like:
sortList(document.getElementsByClassName('list')[0]);
You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.
Example JSFiddle
Edit
Since you mentioned that you want it to happen on pageLoad, I'm assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList to the head of your page and use it immediately after your list like this:
<head>
...
<script type="text/javascript">
function sortList(ul){
var new_ul = ul.cloneNode(false);
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) - parseInt(a.childNodes[0].data , 10);
});
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
</script>
</head>
<body>
...
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
<script type="text/javascript">
!function(){
var uls = document.getElementsByTagName('ul');
sortList( uls[uls.length - 1] );
}();
</script>
...
</body>
You can try this
var ul = $(".list:first");
var arr = $.makeArray(ul.children("li"));
arr.sort(function(a, b) {
var textA = +$(a).text();
var textB = +$(b).text();
if (textA < textB) return -1;
if (textA > textB) return 1;
return 0;
});
ul.empty();
$.each(arr, function() {
ul.append(this);
});
Live example : http://jsfiddle.net/B7hdx/1
you can use this lightweight jquery plugin List.js cause
it's lightweight [only 3K script]
easy to implement in your existing HTML table using class
searchable, sortable and filterable
HTML
<div id="my-list">
<ul class="list">
<li>
<h3 class="name">Luke</h3>
</li>
<li>
<h3 class="name">John</h3>
</li>
</ul>
</div>
Javascript
var options = {
valueNames: ['name']
};
var myList = new List('my-list', options);
There's also this small jQuery plugin. Which would make your sort nothing more than:
$('.list>li').tsort({attr:'id'});
This code will sort that list assuming there is only one .list item:
function sortList(selector) {
var parent$ = $(selector);
parent$.find("li").detach().sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
parent$.append(el);
});
}
sortList(".list");
You can see it work here: http://jsfiddle.net/jfriend00/FjuMB/
To explain how it works:
It gets the .list parent object.
It finds all the <li> child objects.
It removes all the <li> child objects from the DOM, but preserves their data
It sorts the li objects using a custom sort function
The custom sort function gets the HTML in the li tag and converts it to a number
Then, traversing the array in the newly sorted order, each li tag is appended back onto the original parent.
The result is that they are displayed in sorted order.
Edit:
This improved version will even sort multiple list objects at once:
function sortList(selector) {
$(selector).find("li").sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
$(el).parent().append(el);
});
}
sortList(".list");
Demo: http://jsfiddle.net/jfriend00/RsLwX/
Non jquery version (vanilla javascript)
Benefits: the list is sorted in place, which doesn't destroy the LI's nor remove any events that may be associated with them. It just shuffles things around
Added an id to the UL:
<ul id="myList" class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
and the vanilla javascript (no jquery)
// Grab a reference to the UL
var container = document.getElementById("myList");
// Gather all the LI's from the container
var contents = container.querySelectorAll("li");
// The querySelector doesn't return a traditional array
// that we can sort, so we'll need to convert the contents
// to a normal array.
var list = [];
for(var i=0; i<contents.length; i++){
list.push(contents[i]);
}
// Sort based on innerHTML (sorts "in place")
list.sort(function(a, b){
var aa = parseInt(a.innerHTML);
var bb = parseInt(b.innerHTML);
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});
// We'll reverse the array because our shuffle runs backwards
list.reverse();
// Shuffle the order based on the order of our list array.
for(var i=0; i<list.length; i++){
console.log(list[i].innerHTML);
container.insertBefore(list[i], container.firstChild);
}
And the fiddle proof: https://jsfiddle.net/L27gpnh6/1/
You can use this method:
var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
Check the article here:
http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
Edit: There is a very cool jquery plugin that does that : http://tinysort.sjeiti.com/
Something like this should help:
var $parent = $(".list");
$(".list li").sort(function (a, b) {
return window.parseInt($(a).text(), 10) - window.parseInt($(b).text(), 10);
}).remove().each(function () {
$parent.append($(this));
});
One method could be to sort an array (well, a jQuery object) of the li elements and replace the contents (using the html method) of the ul with the sorted array of elements:
$(".list").html($(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}));
Here's a working example.
using jQuery for help:
var sortFunction = function(a, b) {
return (+($(b).text())) - (+($(a).text()));
}
var lis = $('ul.list li');
lis = Array.prototype.sort.call(lis, sortFunction);
for (var i = 0; i < lis.length; i++) {
$('ul.list').append(lis[i]);
}
Fiddle Link
Sort jQuery collection as usual array and then append each element back in correct order.
$(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}).appendTo('.list');
http://jsfiddle.net/zMmWj/

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.

Pure javascript way to update CSS class attribute from all list items?

I'd like to use Javascript (not jquery) to access all items in a <ul> list and remove the active class from everything except my chosen menu item.
Here is the list:
<ul id='flash-menu'>
<li id="menu1" class='something active'>item 1</li>
<li id="menu2" class='somethingelse'>item 2</li>
<li id="menu3" class='somethingelse'>item 3</li>
</ul>
This is my javascript:
function updateMenu(view_name) {
var list_items = document.getElementById('flash-menu').childNodes;
for (var i=0 ; i<list_items.length ; i++){
list_items[i].className = list_items[i].className.replace('/\bactive\b/','');
}
document.getElementById(view_name).className += " active";
}
The last line of the Javascript (adding the active class) works, but I don't think I'm accessing the list items right to remove the classes from the other items. Any suggestions? - thanks!
First off, your regex is wrong:
list_items[i].className.replace(/\bactive\b/, '');
Note: No quotes on regex'es in JavaScript. A slighty altered, working version is available on JsFiddle.
Furthermore, I get a few instances of HTMLTextElements in list_items. They're breaking the loop (Fx3.6/Win7) when trying to access the non-existing className attribute. You can avoid this by either using:
var list_items = document.getElementById('flash-menu').getElementsByTagName('li');
// Selecting _all_ descendant <li> elements
or by checking for the existence of .className before read/write within the loop body (example). The latter is probably the cleanest choice since it still only affects direct children (you may have several levels of <ul>s in each <li>).
I.e.,
function updateMenu(view_name) {
var list_items = document.getElementById('flash-menu').childNodes;
for (var i=0, j=list_items.length; i<j; i++){
var elm = list_items[i];
if (elm.className) {
elm.className = elm.className.replace(/\bactive\b/, '');
}
}
document.getElementById(view_name).className += ' active';
}
You can use javascript function getElementsByTagName:
var listitems = document.getElementsByTagName("li");
this would return an array of all the lists and can be iterated for each list element and processed as required.
You can try:
In the case that you can have more than ul, first you have to get all references to them and then process each ul:
var uls = document.getElementsByTagName("ul");
for (uli=0;uli<uls.length;uli++) {
ul = uls[uli];
if (ul.nodeName == "UL" && ul.className == "classname") {
processUL(ul);
}
}
An illustration of proccessUL can be:
function processUL(ul) {
if (!ul.childNodes || ul.childNodes.length == 0) return;
// Iterate LIs
for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
var item = ul.childNodes[itemi];
if (item.nodeName == "LI") {
// Iterate things in this LI
in the case that you need it put your code here
.....
}
}
}
Of course you can also use: item.className = "classname"; if you dont need to iterate between childs of LI
document.getElementById('flash-menu').childNodes will also include white space nodes.
function updateMenu(view_name) {
var list_items = document.getElementById('flash-menu').getElementsByTagName('li'), i;
for (i=0 ; i<list_items.length ; i++){
if (list_items[i].className.indexOf('active') > -1) {
list_items[i].className = list_items[i].className.replace(/\bactive\b/,'');
}
}
document.getElementById(view_name).className += " active";
}
i agree with jensgram,and you'd better code like this:
list_items[i].className.replace(/\bactive\b/g, '');
add the regex string a 'g'
g is for Global ,using ‘/g’ can replace all the same Which Match the regex ,but if you don't use '/g',you just replace the first string .
like this :
var test= "testeetest" ;
alert(test.replace(/e/,"")) ;//result
: tsteetest but using 'g' var
test= "testeetest" ;
alert(test.replace(/e/g,"")) ;//result
: tsttst
Have a look at this here: https://developer.mozilla.org/en-US/docs/Web/API/element.classList
It helped me a lot with finding class elements!
This is my solution, maybe not the best, but for my works fine.
window.addEventListener('load', iniciaEventos, false);
function iniciaEventos(e)
{
var menu = document.querySelectorAll('nav li');
for(var i = 0; i < menu.length; i++ )
{
menu[i].addEventListener('mousedown', clickMenu);
}
}
function clickMenu()
{
var menu = document.querySelectorAll('nav li');
for(var i = 0; i < menu.length; i++)
menu[i].classList.remove('active');
this.classList.add('active');
}

Categories

Resources