Traverse the DOM and get IDs - javascript

With the following HTML:
<div id="main">
<div id="a">
qq
qw
qe
</div>
<div id="b">
qa
qs
qd
</div>
<div id="c">
qz
qx
qc
qv
</div>
</div>
I want to get a list of all the IDs:
a, a!1, a!3, a!2, b, b!1, b!2, b!3, c, c!1, c!2, c!3, c!4
The following code kind of does that:
var arr = $("#main > div").map(function() {
return this.id
});
var aa = (arr.get().join(","));
alert(aa);
but the alert only gives me" "a,b,c"
Is there a better way to do this that I may be missing so it will transverse the DOM of a specific container ID and pass back all the child IDs of all the elements in the container?

Use css selectors in JQuery to iterate through all, instead of direct children:
$(function(){
$('#main *').each(function (){
var id = $(this).attr('id');
console.log(id);
$('#main').append("<br /> -"+id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="a">
qq
qw
qe
</div>
<div id="b">
qa
qs
qd
</div>
<div id="c">
qz
qx
qc
qv
</div>
</div>

Just do
var arr = $("#main > div, #main > div > a").map(function() {
return this.id
});
Your current code gives the id of direct children of #main but not of a

Just add anchors to query:
$("#main div, #main a")
Codepen

var ids = []
$("a").each(function(){
ids.push($(this).attr("id"))
})

var total_id='';
$('#main *').each(function(){
total_id+=$(this).attr('id')+',';
})
console.log(total_id);
Please try this.

Related

Problem using .sort to sort elements alphabetically

Am having a problem with sorting using jquery.The elements not getting sorted.I used javascript .sort but this works fine with me if the attribute is numbers but not text.
I can solve the issue using append but this is not what am willing to use.
Can some one please trouble shoot this code.
jQuery(document).ready(function($) {
var divList = $(".listing-item");
var gg = divList.get().sort(function(a, b) {
return $(a).data("listing-title") < $(b).data("listing-title");
});
console.log(gg);
$("#list").html(divList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
<div class="listing-item" data-listing-title="a">
a
</div>
<div class="listing-item" data-listing-title="z">
z
</div>
<div class="listing-item" data-listing-title="b">
b
</div>
<div class="listing-item" data-listing-title="c">
c
</div>
</div>
Try using .localeCompare(). I have pull this working content from jQuery - Sorting div contents
<!DOCTYPE html>
<htm>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var divList = $(".listing-item");
divList.sort(function(a, b) {
return $(a).data("listing-title").toUpperCase().localeCompare($(b).data("listing-title").toUpperCase());
});
$("#list").html(divList);
});
</script>
</head>
<body>
<div id="list">
<div class="listing-item" data-listing-title="a">a</div>
<div class="listing-item" data-listing-title="z">z</div>
<div class="listing-item" data-listing-title="b">b</div>
<div class="listing-item" data-listing-title="c">c</div>
</div>
</body>
</html>
See also similar question How may I sort a list alphabetically using jQuery?
you just need to return a number in the sorting function. Return -1 if the first should be placed before the second. So sort ascending
You can add more conditions.
if($(a).data("listing-title") > $(b).data("listing-title")) return 1 -> descending
if($(a).data("listing-title") = $(b).data("listing-title")) return 0 -> no sorting
and put in the HTML the sorted list ( gg instead of divList)
jQuery(document).ready(function($) {
var divList = $(".listing-item");
var gg = divList.get().sort(function(a, b) {
if($(a).data("listing-title") < $(b).data("listing-title")) {
return -1 ;
}
});
console.log(gg);
$("#list").html(gg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
<div class="listing-item" data-listing-title="a">
a
</div>
<div class="listing-item" data-listing-title="z">
z
</div>
<div class="listing-item" data-listing-title="b">
b
</div>
<div class="listing-item" data-listing-title="c">
c
</div>
</div>
you don't need jQuery for this, and I think the problem is your comparison function, something like this, should make the job for you:
//First select the items
const items = document.querySelectorAll('div#list > .listing-item');
//Next, transform this to an array using `from`, then compare
//using `sort`, finally iterate over the sorted array using `forEach`,
//and append element in the sorted array to the `#list`.
//
Array
.from(items)
.sort((x,y) => {
const valueX = x.dataset.listingTitle;
const valueY = y.dataset.listingTitle;
if(valueX > valueY) return 1;
else if(valueX < valueY) return -1;
else return 0;
})
.forEach(element => document.getElementById('list').appendChild(element));

looking for a good pratice to hide and display some divs

Hello everybody I would like to hide some divs and display others when I click on a specifiks links.
Actually I did like this :
<html>
<head>
<script>
function loadA(){
document.getElementById("A").style.display="block";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadB(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="block";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadC(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="block";
document.getElementById("D").style.display="none";
}
function loadD(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="block";
}
</script>
</head>
<body>
<div class="menu">
A
B
C
D
</div>
</body>
</html>
This is work with me but as you see it's not a good practice and sure there is another way better than this , can you show me please !
A solution without javascript:
.container > div{
display:none
}
.container > div:target{
display:block
}
<div class="menu">
<a href="#A" >A</a>
<a href="#B" >B</a>
<a href="#C" >C</a>
<a href="#D" >D</a>
</div>
<div class="container">
<div id="A" >A content</div>
<div id="B" >B content</div>
<div id="C" >C content</div>
<div id="D" >D content</div>
</div>
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Atarget
https://css-tricks.com/css3-tabs/
You can create one function and reuse it for each element:
function loadDiv(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
And pass the correct id into each onclick:
<div class="menu">
A
B
C
D
</div>
Here's how you should do it. No inline javascript, handling click events with an eventListener and wrapping all elements together with a class, making it much less code to write and maintain:
JS:
function divLoader(e){
var hide = document.getElementsByClassName("hideAndShow");
for (var i = 0; i<hide.length;i++) {
hide[i].style.display="none";
}
document.getElementById(e.target.getAttribute('data-link')).style.display="block";
}
var anchors = document.querySelectorAll('.menu > a');
for (var i = 0; i<anchors.length; i++) {
anchors[i].addEventListener('click',divLoader);
}
HTML:
<div class="menu">
A
B
C
D
</div>
<div id="A" class="hideAndShow" style="display:none;">A</div>
<div id="B" class="hideAndShow" style="display:none;">B</div>
<div id="C" class="hideAndShow" style="display:none;">C</div>
<div id="D" class="hideAndShow" style="display:none;">D</div>
In such cases where you have similar repetitive code you can use a common technique called "Abstraction". The main idea is the turn the common code into parameters of a single function in your case it would be:
function loadByID(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
However this is also still a little bit redundant, for larger menus and displaying multiple links you can do something like
function loadByIDs(ids){
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
document.getElementById(links[i].id).style.display = none;
}
for each(var id in ids){
document.getElementById(id).style.display = block;
}
}
This will work much better when you have too much links and want to display more than one link at a time (so you will need to pass in an array)
Note: If you are using Jquery you can just use .each() function to get rid of the first for loop
Hope this helps!
I think the best practice in your case is to define a general function that work however the number of links with specific class in my example the class is link, take a look at Working Fiddle.
Now your script will work with dynamic links added in div, you have just to add html without touching the js will detect change.
HTML :
<div class="menu">
A
B
C
D
</div>
JS :
load = function(e){
//select all links
var links = document.getElementsByClassName('link');
//Hide all the links
for (i = 0; i < links.length; i++) {
links[i].style.display = "none";
}
//Show clicked link
e.target.style.display = "block";
}
Hope this make sens.
HTML
<body>
<div id="main">
<ul id="nav">
<li>Home</li>
<li>About Us</li>
</ul>
<div id="container">
<div id="wrapper">
<div class="content">
<div id="menu_home">
<h2>Menu 1</h2>
</div>
<div id="menu_about">
<h2>Menu 2</h2>
</div>
</div><!--content-->
</div><!--wrapper-->
</div><!--container-->
</div><!-- main-->
</body>
JS
$(document).ready(function(){
$("#menu_home").slideUp("fast");
$("#menu_about").slideUp("fast");
$("#menu_home").show();
$("#nav a").click(function(){
var id = $(this).attr('id');
id = id.split('_');
$(".content div").slideUp("fast");;
$(".content #menu_"+id[1]).slideToggle("fast");
});
});
Here is the example
function loadA()
{
document.getElementById("A").style.visiblity="show";
document.getElementById("B").style.visiblity="hide";
document.getElementById("C").style.visiblity="hide";
document.getElementById("D").style.visiblity="hide";
}
if visibility dont work,just change the visibility keyword with visible and hide with hidden.
and one more thing,u should not write function for each div..what can u do just pass id of a div which u want to show and hide others..see below
function trigger(id)
{
var alldiv={"A","B","C","D"};
for(i=0;i<alldiv.length;i++)
{
if(alldiv[i]==id)
document.getElementById(id).style.visiblity="show";
else
document.getElementById(alldiv[i]).style.visiblity="hide";
}
}

tSort on jQuery object

I'm trying to sort the results of a jQuery selection with tSort.
HTML:
<div sort="2"></div>
<div sort="3"></div>
<div sort="1"></div>
<div sort="4"></div>
<div sort="6"></div>
<div sort="5"></div>
Javascript:
<script>
$sort_order = $('div').tsort({attr:'sort'});
</script>
I want the result to be: 1,2,3,4,5,6 in the jQuery object, not yet inserted into the page.
Is this possible with tSort, or should I write my own algorithm?
It is easier to do it if there is a wrapper of all the div elements.
HTML:
<div id="wrapper">
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
Javascript (with jQuery):
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
Working demo.
In response to #Tim's comment, you can place the elements that do not have the sort attributes at the back of the wrapper element easily, even without jQuery.
Assuming that this is your HTML:
<div id="wrapper">
<div style="color:red;">red color, without sort attribute</div>
<div style="color:red;" sort="7">red color (sort attribute=7)</div>
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
You can place the element(s) that do not have the sort attribute by having this as your Javascript:
// As shown earlier above,
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
// New code to add:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].getAttribute('sort') == null || divs[i].getAttribute('sort') == undefined) {
divs[i].parentNode.appendChild(divs[i]);
}
}
Working demo.
clone it before using .tsort
$sort_order = $('div').clone().tsort({attr:'sort'});
DEMO

Check Div Elements by name fast

I have some Divs:
<div id="content">
<div class="c" id="1">
<div id="xyz">dont care</div>
<div id="texts1">
<div name="check"> ContentText </div>
</div>
</div>
<div class="c" id="2">
<div id="xuyz">dont care</div>
<div id="texts2">
<div name="check"> ContentText </div>
</div>
</div>
</div>
I want to iterate through all elements of the "c" class.
Then I want to check, if the Div elements named "check" of each "c" element contains special text.
If true, then manipulate the "c" element (which contains the special text)
I tried something like this:
var ele = document.getElementsByClassName("c");
for(var i=0;i<ele.length;i++)
{
var check = ele[i].getElementsByName("check");
if(check.innerHTML ....)
}
But thats not working :/
Log from Firefox:
TypeError: ele[i].getElementsByName is not a function
Where is my mistake?
A simple querySelectorAll() should do the trick:
var check = document.querySelectorAll('.c [name="check"]');
And as stated in a comment already, only document has getElementsByName method.
With jQuery this is very simple -
$('[name="check"]:contains("your special text")')
With jQuery (you have tagged it with it as well)
$(document).ready(function () {
$('div.c').find('div[name="check"]').each(function(){
// here check HTML and do needed manipulations
if($(this).html() == 'ContentText'){
$(this).closest('div.c').children().first().html('I CARE');
}
});
});
see jSFiddle -> http://jsfiddle.net/ApfJz/32/
Here is a modification of your code to make it work as intended
var ele = document.getElementsByClassName("c");
for (var i = 0; i < ele.length; i++)
{
if (ele[i].getAttribute('name') === "check") {
// do something with matching elements here
}
}

How to set height of parent, dependent on height of selected element

I have a scenario where I want to find all elements with a certain class, and then I want to set the parent div's padding-bottom value as the sum of its current padding-bottom value + the height of the original div which matched the selector.
So say I have a structure like this:
<div class='A'>
<div class='B'>
<div class='C'>
.........
</div>
<div class='D'>
.........
</div>
</div>
<div class='B'>
<div class='C'>
.........
</div>
</div>
<div class='B'>
<div class='C'>
.........
</div>
</div>
<div class='B'>
<div class='D'>
.........
</div>
</div>
</div>
I want to find all class D objects, and then I want to set the padding bottom value of their container class B, to the height of the class D object in question, plus whatever padding-bottom value that class B object currently has ..
Note that all class D objects have different heights ..
Every class B objects can only have a max of 1 class D object
Every class B objects can only have a max of 1 class C object
What jQuery do I need to do the above ?
Try this:
$('.D').each(function(){
$(this).parent().css("paddingBottom", "+=" + $(this).height() +"px");
});
Demo.
$(function(){
$('div.D').each(function(index){
var dHeight = $(this).height();
var bPadding = $(this).parent().css('padding-bottom');
var newPadding = parseInt(dHeight) + parseInt(bPadding);
$(this).parent().css('padding-bottom', String(newPadding) + 'px');
});
});
This should the solution for the problem that you've described. But I think you've missed some details. (this code might be shortened to a one liner though)
$(function() { 'use strict';
$('.A > .D').each(function() {
var $D = $(this);
var $B = $D.closest('.B');
$B.css('padding-bottom',
$D.height() + parseInt($B.css('padding-bottom'))
);
});
});
In case you want to include the height of the .C elements too:
$(function() { 'use strict';
$('.A > .D, .A > .C').each(function() {
var $X = $(this);
var $B = $X.closest('.B');
$B.css('padding-bottom',
$X.height() + parseInt($B.css('padding-bottom'))
);
});
});

Categories

Resources