How can I get the data from div already divided - javascript

Hi everyone I want to extract data from divs using Jquerys.
So I have this 3 div :
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>
In my JS file I want to extract: Venice,it / Madrid,es / Rome,it.
What I did for now is: var data = $("div.wind").text() .
Writing this I get the string Venice,itMadrid,esRome,it but I don't want to this. I want the div splitted already like.
var vector= [(Venice,it),(Madrid,es),(Rome,it)]
How can I do this?
Thank you in advance for your help.

Use .each()
$(() => {
var vector = []
$(".wind").each(function(){ vector.push($(this).text()) })
console.log(vector)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>

const divs = $("div.wind");
const data = divs.toArray().map(d => d.textContent)

just use push on the innerHTML
var myArray=[];
var div =document.getElementsByTagName('div');
for(let i=0;i<div.length;i++){
myArray.push(div[i].innerHTML);
}
console.log(myArray);
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>

You can use jQuery's .each to iterate through each div selected. You can then get the .text() value for each div one by one, and push the value into the vector array.
Demo:
var vector = [];
$("div.wind").each(function(index, div) {
var data = $(div).text();
vector.push(data);
});
console.log(vector);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wind">Venice,it</div>
<div class="wind">Madrid,es</div>
<div class="wind">Rome,it</div>

Related

How to display the last four blog posts using JSON API in div tag

How do I display the latest four blog post WordPress API in HTML
HTML:
<div id="content" class="content"></div>
JavaScript:
<script>
$(document).ready(function() {
$.getJSON("https://startupet.com/blog/wp-json/wp/v2/posts", function(data) {
console.log(data);
});
})
</script>
I'm getting image post and title
JSON file: https://startupet.com/blog/wp-json/wp/v2/posts
You can use slice with a negative number to get the element from the end of the array.
In this example , dummy api is returning a response and slice(-4) is used to get the last 4 elements, then iterate that array and create the dom
$.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {
let string = '';
data.slice(-4).forEach(function(item) {
string += `<div>${item.title}</div>`
})
$("#content").append(string)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>
You can sort the array based on the timestamp and slice it with the number of items you require.
Next is to iterate through the result and display however you want in the html
$(document).ready(function(){
$.getJSON( "https://startupet.com/blog/wp-json/wp/v2/posts",
function(data) {
const result = data.sort((a,b) => (a.date > b.date)).slice(Math.max(data.length - 4, 1));
console.log(result); // Your Result contains the last 4 posts sorted by date
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>

Sorting out array of parent child relations where two children share a parent from an array and display it using div

I have the following data which gets served from a neo4j query, The data that gets sent back is in the format
home->parent->child1
home->parent->child2
home->parent2->child1
home->parent3->child1
home->parent3->child2
home->parent3->child3
I am trying to use javascript to display html which should be like this
<div id="parent1">
<div id="child1"></div>
<div id="child2"></div>
</div>
<div id="parent2">
<div id="child1"></div>
</div>
i tried loopong throigh the query and trying to get the parent to be the index of an object and the child to be values under it
i would do this like this in php
$jsonContents = (object)("parent"=>"child","parent"=>"child"....);
$array = array();
foreach($jsonContents as $jsCo=>$jsoCont){
$array[$jsoCont->parent][] = $jsoCont->child;
}
this would return the
$array as
home->parent1->[0]->child
->[1]->child
parent2->[0]->child...
This would let me avoid the check for uniqueness of the home parent category as well as put them in a hierarchy so i can interpret it properly in my View part of MVC, to create my div structure.
this is the url for the example json data
http://www.jsoneditoronline.org/?id=bdda268982eb431d361c25e9035bbc99
No answers to this, solved it by myself.
Here
var data = 'data shown in link above';
var myArr = [];
$.each(data, function(index, element) {
var parent = String(element.parent.properties.name);
var child = String(element.child.properties.name);
if(myArr[parent]){
myArr[parent][(myArr[parent].length)] = child;
} else {
myArr[parent] = Array(child);
}
});
Hope this helps people. :)

Get values from elements inside DIV

I need to get values inside div on clicking a button, wich locates inside this div. Here is the html structure:
<div class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
When I click on .button-buy-modal, I need to get values from .products__title .products__price and .products__id, but the problem is that we have a lot same div's (product cards), and a lot of buttons inside them. I think that I should use something like $(this), but actually I don't know how.
I'm trying to test something like this, but it doesn't work:
$("a.button-buy-modal").click(function () {
$(this).find().closest('.products__priceholder').addClass('test1');
})
Here is a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})
$(this).parent().parent().find('.products__price').text()
will give you this - "86 590 руб."
$(this).parent().parent().find('.products__price').html()
will give you this -- "<strong>86 590</strong> руб."
To learn more about it as in how you can select any particular DOM element and read it or manipulate it etc, read here - http://api.jquery.com/category/selectors/
You can add an id to your parent div or use eq(x) to select the right group.
<div id="mydiv1" class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
Then with jQuery:
var title = $('#div1 .products__title').html();
/// OR
var title = $('.products__item:eq(0) .products__title').html();
var price = $('#div1 .products__price').html();
/// OR
var price = $('.products__item:eq(0) .products__price').html();
price = price.replace(/<[^>]+>/g, ""); // regex to remove tags
EDIT
If you want to use .closest(), you don't need .find()
$("a.button-buy-modal").click(function () {
$(this).closest('.products__priceholder').addClass('test1');
});
Thank's all for advices, I found a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})

Get concatenated text of elements using JavaScript

I tried it with getElementById and it worked. But now I want the same with multiple div's so I have to use classes. So I changed the method to getElementsByClassName and now it says undefined.
(The function is called when a option in a select changes. This works correctly)
HTML:
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>
Javascript:
function sorting(sortingway) {
alert(sortingway.value);
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = titelfilms.innerHTML;
console.log(titels[0]);
}
Is there a way to do this without jQuery?
getElementsByClassName returns a collection, so loop that!
var titelfilms = document.getElementsByClassName("filmnaam");
for (var i = 0; i < titelfilms.length; i++) {
var titels = titelfilms[i].innerHTML;
console.log(titels);
}
titelfilms is a node list, you can't get the innerHTML of a node list as a whole, it contains multiple references to elements which each have their own individual property.
You could loop through and concatenate each innerHTML onto a variable, or you could map() the innerHTML of your returned elements to an array and then join() them up:
function sorting(sortingway) {
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = Array.prototype.map.call(titelfilms, function (el) {
return el.innerHTML;
}).join(' ');
console.log(titels);
}
sorting();
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>

sorting elements using jquery

I have a div, #containerDiv, which contains elements related to users like first name, last name etc. in separate divs. I need to sort the contents of the container div based on the last name, first name etc. values.
On searching google the examples I got all are appending the sorted results and not changing the entire HTML being displayed. They are also not sorting by specific fields (first name, last name).
So please help me in sorting the entire content of #containerDiv based on specific fields and also displaying it.
The Page looks Like something as mentioned Below:
<div id="containerDiv">
<div id="lName_1">dsaf</div><div id="fName_1">grad</div>
<div id="lName_2">sdaf</div><div id="fName_2">radg</div>
<div id="lName_3">asdf</div><div id="fName_3">drag</div>
<div id="lName_4">fasd</div><div id="fName_4">gard</div>
<div id="lName_5">dasf</div><div id="fName_5">grda</div>
<div id="lName_6">asfd</div><div id="fName_6">drga</div>
</div>
On getting sorted by last name div values, the resulted structure of the container div should look like:
<div id="containerDiv">
<div id="lName_3">asdf</div><div id="fName_3">drag</div>
<div id="lName_6">asfd</div><div id="fName_6">drga</div>
<div id="lName_5">dasf</div><div id="fName_5">grda</div>
<div id="lName_1">dsaf</div><div id="fName_1">grad</div>
<div id="lName_4">fasd</div><div id="fName_4">gard</div>
<div id="lName_2">sdaf</div><div id="fName_2">radg</div>
</div>
Now I think you all can help me in a better way.
this is a sample example:
html:
<div id="containerDiv">
<div>2</div>
<div>3</div>
<div>1</div>
</div>
js
$(function() {
var container, divs;
divs = $("#containerDiv>div").clone();
container = $("#containerDiv");
divs.sort(function(divX, divY) {
return divX.innerHTML > divY.innerHTML;
});
container.empty();
divs.appendTo(container);
});
you may set your divs.sort function param depend on your goal.
jsFiddle.
and a jQuery Plugin is suitable
I suggest you read the div values so you get an array of objects (persons for example) or just names and perform a sort operation on that. Than...output the result to the initial div (overwriting the default values).
I have built a jQuery sort function in which you can affect the sort field.
(it rebuilds the html by moving the row to another location).
function sortTableJquery()
{
var tbl =$("#tbl tr");
var store = [];
var sortElementIndex = parseFloat($.data(document.body, "sortElement"));
for (var i = 0, len = $(tbl).length; i < len; i++)
{
var rowDom = $(tbl).eq(i);
var rowData = $.trim($("td",$(rowDom)).eq(sortElementIndex).text());
store.push([rowData, rowDom]);
}
store.sort(function (x, y)
{
if (x[0].toLowerCase() == y[0].toLowerCase()) return 0;
if (x[0].toLowerCase() < y[0].toLowerCase()) return -1 * parseFloat($.data(document.body, "sortDir"));
else return 1 * parseFloat($.data(document.body, "sortDir"));
});
for (var i = 0, len = store.length; i < len; i++)
{
$("#tbl").append(store[i][1]);
}
store = null;
}
Every time I need to sort lists I use ListJs.
It's well documented, has good performance even for large lists and it's very lightweight (7KB, despite being library agnostic).

Categories

Resources