map multiple div elements into array - javascript

Faced with mapping problem, it returns for me a blank array with two empty elements. Having a button where on click it gets related div block, then I'm trying to get type and number and push them into array. What I am doing wrong here?
<div class="chapter">
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
</div>
function func(el) {
let block = $(el).closest("div.chapter")
let arr = $(block.find('.contact')).map(function () {
let val = $(this).find('.type, .number').val();
return val;
}).get();
console.log(arr) //result: ["", ""]
}

The .val() method is primarily used to get the values of form elements such as input, select and textarea. You need to use text() method for this, as text() string containing the combined text of matched elements.
Using .val() on span element:
console.log( $('.type').val() )
// Return empty string
console.log( typeof $('.type').val() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Using .text() on span element:
console.log( $('.type').text() )
// Returns '2'
console.log( typeof $('.type').text() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Also call them individually for each element like this:
let arr = block.find('.contact').map(function() {
let type = $(this).find('.type').text().trim();;
let number = $(this).find('.number').text().trim();;
return { type, number};
}).get();
This will return you array of objects, where each object has text content of type & number class elements.
DEMO:
let arr = $('.span').find('.contact').map(function() {
let type = $(this).find('.type').text().trim();
let number = $(this).find('.number').text().trim();
return { type, number};
}).get();
console.log( arr )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>

Your code does not match with the HTML markup you have provided. You can simply loop through all the element with class contact and find the element inside with specific class to from the object.
Please Note: The span element does not have the value property, you have to use .text().
function func() {
let arr = $('.contact').map(function () {
return {
type: +$(this).find('.type').text().trim(), //find text and convert to number using +
number: +$(this).find('.number').text().trim()//find text and convert to number using +
}
}).get();
console.log(arr);
}
func();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>

you can use simple JavaScript it's easy!
document.querySelectorAll(".contact").forEach((elm)=>{
arr=[] ;
arr.push(elm.children[0].innerText);
arr.push(elm.children[1].innerText);
console.log(arr)
})

Related

How to get PreviousAll element Child class using jquery

How to get previous all element class list using jquery.
Here is the Example.
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>
I want all the class names above in "getclass" id.
And i'm trying the below things.
var a = $("#getclass").prevAll().find('.class').attr('class');
How can i achive this using jquery.Anyone please Help me to fix this issue.
Your code is looking for elements with the class class.
You can instead get all children of previous siblings and then use the map function to convert this to an array with just class names by returning the className property.
Example:
var a = $("#getclass")
.prevAll()
.children("span")
.get()
.map(function(x) {
return x.className;
});
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>
You can read each element through a loop:
<script type="text/javascript">
$(function () {
var classes = [];
$("#getclass").prevAll().each(function () {
classes.push($(this).find('span').attr('class'));
});
var classNames = classes.join(",");
alert(classNames);
});
classes is an array of class names, you can also get it as a CSV.

Iterating through data-* elements using JQuery $.children() and $.each()?

I want to be able to iterate through my HTML code and pick every element that harbors the "data-" attribute and collect it's value. I have looked on the web and only found ways to collect data on specific data- elements. I need to get the data-* value without knowing the element name, and so I found the .children() jquery method. However I don't know how to implement it all together.
Here's a quick example of what I'm doing:
HTML:
<div data-example="master">
<div data-example="i">
<div data-example="a">
<span data-example="1"></span>
</div>
<div data-example="b">
<span data-example="2"></span>
</div>
</div>
<div data-example="ii">
<div data-example="c">
<span data-example="3"></span>
</div>
<div data-example="d">
<span data-example="4"></span>
</div>
</div>
</div>
JavaScript:
var master = [];
$("#master").children(function() {
var element = $(this);
var data = element.data('example');
master.push(data);
}
So for this particular example, I want my end-game to have the master array equal [i, a, 1, b, 2, ii, c, 3, d, 4].
But I'm not doing it right because nothing is happening when I trigger the JQuery event.
Use Attribute selector and apply Array.prototype.map over it.
console.log(Array.from($('[data-example]')).map(function(elem) {
return $(elem).data('example');
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-example="master">
<div data-example="i">
<div data-example="a">
<span data-example="1"></span>
</div>
<div data-example="b">
<span data-example="2"></span>
</div>
</div>
<div data-example="ii">
<div data-example="c">
<span data-example="3"></span>
</div>
<div data-example="d">
<span data-example="4"></span>
</div>
</div>
</div>

jquery - select an element with specific content

I have an html structure like this:
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
In my javascript code, I need to get an <span> element with class content that has exactly 1 or 2 , ..., 100
I tested jquery .contains method, but this returns all elements that have for example 1. such as 1, 12, ....
You can use filter method which accepts a callback function applied to every item.
var array=$('.test').find('.content').filter(function(){
return $(this).text().trim()==100;
});
console.log(Array.from(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
You can proceed in the following manner:
$('.content').each(function(){
if($(this).html() == "2")
{
console.log("THE SPAN WITH 2 IS ");
console.log($(this)[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
What we do here is check through the content class of the spans and check if their inner html is 2 and if it is we console.log it.
You can use the vanilla .indexOf() method.
The indexOf method takes a parameter of the string you want to find and returns either the index (if it's found), or -1 if it's not.
var myEl = document.querySelector(".test"):
for loop...
if( myEl.innerHTML.indexOf(2) != -1 ){
console.log("This element contains the number 2")
}
You can use .filter(), get and check .textContent or .innerHTML of element, at .filter() callback you can use RegExp N$ where N is number to match. For example, to match elements having "1" or "2" set at .textContent you can use RegExp /1$|2$/; to match "100", /100$/; with RegExp.prototype.test()
var filtered = $("span.content").filter((_, {textContent}) =>
/1$|2$/.test(textContent));
filtered.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
You can do something like this..
$('.test').each(function() {
if($(this).text == '1')
{
var a = $(this).html();
}
});
a will now contain the html of that span which contains your text.

Copy multiple element value and append text after in jQuery

I have price span tags on my page:
<div>
<span class="priceTitle">10.00</span>
</div>
<div>
<span class="priceTitle">15.00</span>
</div>
<div>
<span class="priceTitle">20.00</span>
</div>
I want to append after the span tag the value of the span multiplied by a number.
Somehow like this:
$( ".priceTitle" ).after( $( ".priceTitle" ).val()*1.20 );
...but this is not working.
span does not have a .value property. Use .each() to iterate .priceTitle elements, + operator and .textContent of element to convert string to number; chain .toFixed(2) if you are expecting decimal and two zeroes following product of multiplication.
$(".priceTitle")
.each(function() {
$(this).after(" " + (+this.textContent * 1.20).toFixed(2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="priceTitle">10.00</span>
</div>
<div>
<span class="priceTitle">15.00</span>
</div>
<div>
<span class="priceTitle">20.00</span>
</div>

Sort HTML String

I have this bit of HTML code.
<div class="container">
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">35000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2101</span>
<span class="cabin">Economy</span>
<span class="price">40000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">22000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">14500</span>
</div>
</div>
How do I sort it -- based on price -- using Javascript? Please, don't ask me for my JS code. My only thought was to use the bubble sort algorithm. But then, bubble sort works only on sorted arrays and my HTML string isn't sorted. Any suggestions, pointers and / or code will be appreciated.
Create an array and insert for each element 2 fields, the HTML element and the price, sort the array, re-insert the elements after sorting to conainer after make it empty:
var elements = document.querySelectorAll('.single-result');
var sortable = [];
for (i=0;i<elements.length;i++){
sortable.push([elements[i], elements[i].querySelector('.price').textContent]);
}
sortable.sort(function(a, b) {return a[1] - b[1]});
container = document.querySelector('.container');
container.innerHTML = "";
sortable.forEach(function(item) {
container.appendChild(item[0]);
});

Categories

Resources