Get the middle value of a class using JQuery - javascript

How can I get the third and forth value of class="myDivs" using jQuery?
Below is my code:
HTML :
<div class="myDivs">Stack</div>
<div class="myDivs">Over</div>
<div class="myDivs">Flow</div>
<div class="myDivs">And</div>
<div class="myDivs">Exchange</div>
<div class="myDivs">Question</div>
<div class="myDivs">Ask</div>

You can use :eq to get the element at particular indexes.
Live Demo
$('.myDivs:eq(2), .myDivs:eq(3)').each(function(){
alert($(this).text());
});
Using the combination of :gt and :lt will give you range. It is useful when you have many elements.
Live Demo
$('.myDivs:gt(1):lt(2)').each(function(){
alert($(this).text());
});
Edit To make it dynamic so that you do not have to hard code the middle you can divide the length of element collection and use it for start point, this will make it work independant of how many elements you have with class myDivs.
Live Demo
mid = Math.floor($('.myDivs').length /2) -2;
$('.myDivs:gt(' + mid +'):lt(2)').each(function(){
alert($(this).text());
});

You can use .slice()
Reduce the set of matched elements to a subset specified by a range of
indices
and push the text value into an array using .map():
var valArr = $('.myDivs').slice(2,4).map(function() {
return this.textContent;
}).get();
Fiddle Demo

One dynamic way is to calculate by the length of class count.
var mid1=Math.ceil($('.myDivs').length/2) - 1,
mid2=Math.floor($('.myDivs').length/2) - 1;
if(mid1===mid2){
//handle the case
}
$('.myDivs:eq('+mid1+'), .myDivs:eq('+mid2+')').each(function(){
alert($(this).text());
});
Here is demo

Reference them by index
var myDivs = $('.myDivs'),
third = myDivs.eq(2),
fourth = myDivs.eq(3);
To get the text value, just use text()

use
$( "div:nth-child(3)" ).html();
$( "div:nth-child(4)" ).html();
it will return you text of 3 and 4 div text
Fiddel

jQuery has a simple get function
http://api.jquery.com/eq/
var $myDivs = $(".myDivs");
var nr3 = $myDivs.eq(2);
var nr4 = $myDivs.eq(3);

If you are planning to perform same operation on both the third and fourth divs, then use the following code:
$('.myDivs:eq(2), .myDivs:eq(3)').each(function(){
// perform your operation here
});
If you want to perform different tasks on both of them, then
var myDivs = $(".myDivs"),
thirdDiv = myDivs[2],
fourthDiv = myDivs[3];
Now you can bind custom events to those particular divs alone.
for example :
$(thirdDiv).click(function() {
// custom function
});

Related

Sorting divs based on array order

I have a drag and drop design that, when you rearrange the draggable items, pushes their ids to an array. So i’ll have an array like:
["#fake-block_1","#fake-block_3","#fake-block_2"]
Behind the scenes, I want to rearrange some corresponding divs that share the same numeric value as these blocks, e.g., #fake-block_1 maps on to #real-block_1. I can’t quite seem to grasp how I would get this rearrangement to happen. Heres what I currently have:
$('.js-fake-block’).each(function(i){
$this = $(this);
$array = new Array();
$delimiter = '_';
$array.push($this.attr("id").split($delimiter)[1]);
$array.forEach(function(item,index){
$realBlockId = "#real-block_”+[item];
});
});
So I loop through every “fake block”, split their ID by an underscore (I match fake and real with the same numeric value), add them into an array, and then have the real Ids made up again… but after that I’m lost. No idea how I’d sort the “real blocks” based on this "fake blocks" arrays order.
Here is a simple example of what you're trying to do JSFiddle
function sortDom(selectorArray) {
while (selectorArray.length) {
let $el = $(selectorArray.pop());
$el.parent().prepend($el);
}
}
//Usage//
$('.ordinal').on('click', function() {
sortDom(['#_01', '#_02', '#_03', '#_04', '#_05', '#_06', '#_07', '#_08', '#_09', '#_10']);
});
$('.reversed').on('click', function() {
sortDom(['#_10', '#_09', '#_08', '#_07', '#_06', '#_05', '#_04', '#_03', '#_02', '#_01']);
});
$('.jumbled').on('click', function() {
sortDom(['#_07', '#_01', '#_10', '#_04', '#_02', '#_03', '#_06', '#_05', '#_09', '#_08']);
});
Note this method does not enforce the array elements reference dom elements attached to the same parent and it does not enforce that all child elements of the parent must be referenced in the array. Unreferenced child elements will be pushed to the bottom of the list.
One solution is to use the sort method to describe how to the sort elements and then re-set the html of the parent:
var sortedDivs = $divs.sort(function (a, b) {
// If referring to your array of IDs, you can use indexOf($(a).attr("id"))
return $(a).attr("id") > $(b).attr("id");
});
$("#container").html(sortedDivs);
JsFiddle
I don't know why you need to save numbers in array and loop again to create a new array .. you can just use the next code
$array = []; // use array outside the loop
$('.js-fake-block').each(function(i){
var $this = $(this);
var $delimiter = '_';
var SplitNum = $this.attr("id").split($delimiter);
$array.push("#real-block_" + SplitNum[1]);
});
console.log($array);
Working example
$array = []; // use array outside the loop
$('.js-fake-block').each(function(i){
var $this = $(this);
var $delimiter = '_';
var SplitNum = $this.attr("id").split($delimiter);
$array.push("#real-block_" + SplitNum[1]);
});
console.log($array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js-fake-block" id="fake-block_1"></div>
<div class="js-fake-block" id="fake-block_3"></div>
<div class="js-fake-block" id="fake-block_5"></div>
<div class="js-fake-block" id="fake-block_4"></div>
<div class="js-fake-block" id="fake-block_2"></div>

Select element by tag/classname length

I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Get DIV ID where Class is selected?

I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/

How to iterate through an HTML table column and input the values into a Javascript array using JQuery

Let's say I have a table column with 10 rows, each with <td id="num"> and a text value.
How can I use JQuery to loop through each row in the column and input the spins into a Javascript array?
I thought the following code would do it, but it is only getting the first element:
var numArray = [];
$("#num").each(function(n){
numArray[n] = $(this).text();
});
Any ideas?
Thanks!
You can't have multiple elements with the same id. This isn't allowed because the id is used to identify individual elements in the DOM. I'd suggest giving them all the same class, which is allowed.
<td class="num">
Then this should work:
var numArray = [];
$(".num").each(function(n){
numArray[n] = $(this).text();
});
Like mcos said, selecting by id for all the tables doesn't work. There can only be one item on a page with a given id.
You can either give your table an id and do the following:
var numArray = [];
// Assuming #my-table-id is your table and you want all the tds
$("#my-table-id td").each(function(n){
numArray[n] = $(this).text();
});
Or if you don't want all the tds, use a class to identify the ones you want
var numArray = [];
// Assuming #my-table-id is your table and you added class="collect"
// to the tds you want to collect
$("#my-table-id td.collect").each(function(n){
numArray[n] = $(this).text();
});
Also stealing from others answers, the map function can also help you make your code even smaller
var numArray = $.map( $("#my-table-id td.collect"), function (td){
return $(td).text();
})
You can achieve the this with using .text(function(i, text){})
var allText = [];
$("table td").text(function(i, t){
allText.push(t);
});
Code example on jsfiddle
If you need to target a particular cell(s) you can just modify the selector.
$("table td#num").text(function(i, text){
allText.push(text);
});
With that being said, an id should be unique per dom and if you can adjust the html using a class would be the right way.
<td class="num">
some text 1
</td>
$("table td.num").text(function(i, text){
allText.push(text);
});
Example
it's advised that use don't reuse the ID but since it'll html.. it'll still work..
the jQuery ID(#) selector will only select the first match...
you can use the td[id^='num'] or td[id*='num'] or td[id$='num'] instead
use the map ..
var numArray = $("td[id^='num']").map(function(){
return $(this).text();
}).get();
This will select all the td's with ID's starting as num
See it here

Categories