How to push element attribute value into javascript array? - javascript

This is my html structure. Here, i have created two attributes for each element. How to push attribute value into an array (like this structure, [[1,0],[1,1],[1,2],[0,2],[2,2],[1,3],[1,4]])?
<div id="demo">
<div data-floor="1" data-floor-sub="0">Div1</div>
<div data-floor="2" data-floor-sub="0">Div2</div>
<div data-floor="3" data-floor-sub="0">Div3</div>
<div data-floor="3" data-floor-sub="1">Div4</div>
<div data-floor="3" data-floor-sub="2">Div5</div>
<div data-floor="4" data-floor-sub="0">Div6</div>
<div data-floor="5" data-floor-sub="0">Div7</div>
</div>

Use map()
var multiDimArray = $('#demo div').map(function() {
var innerArray = [];
innerArray.push([$(this).data('floor'), $(this).data('floor-sub')]);
return innerArray;
}).get();
console.log(multiDimArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="demo">
<div data-floor="1" data-floor-sub="0">Div1</div>
<div data-floor="2" data-floor-sub="0">Div2</div>
<div data-floor="3" data-floor-sub="0">Div3</div>
<div data-floor="3" data-floor-sub="1">Div4</div>
<div data-floor="3" data-floor-sub="2">Div5</div>
<div data-floor="4" data-floor-sub="0">Div6</div>
<div data-floor="5" data-floor-sub="0">Div7</div>
</div>

Related

jquery hiding an array of id

I am trying to build a bookmarklet that will hide all data-agentid selectors that have a data-color selector = 30. so I have a list on the website that look something like this
<div class="sch" data-agent-id=1></div>
<div data-agentid="1" data-color="30">
<div data-agentid="1" data-color="20">
...
<div class="sch" data-agent-id=2></div>
<div data-agentid="2" data-color="10">
<div data-agentid="2" data-color="20">
...
...
edited
There is a lot more code but I figure this is the important part.
I am thinking I can just build an array of ids where their color is 30 and then hide all of the ids in the array. My code is below but I don't think it is even building the array at this point.
(function() {
var arr = $('*[data-color="30"]').map(function() {
return $(this).data("data-agentid");
}).get().join();
$('*[data-agent-id=arr]').hide();
})();
Seems like you would just do this directly:
$('[data-color="30"]').hide()
Edit: Now that you've clarified what you're trying to do, it'll be more performant to select the elements once and iterate over them calling hide on the matching ones:
const agentsToHide =
Array.from(document.querySelectorAll('[data-color="30"'))
.reduce((agents, el) => {
const agentId = el.getAttribute("data-agentid")
if (!agents.includes(agentId)) agents.push(agentId)
return agents
}, [])
.forEach(agentId => {
document.querySelectorAll(`[data-agent-id="${agentId}"]`)
.forEach(el => {
el.style.display = "none"
})
})
<div class="sch" data-agent-id=1>Agent 1</div>
<div data-agentid="1" data-color="30">30</div>
<div data-agentid="1" data-color="30">30</div>
<div data-agentid="1" data-color="20">20</div>
<div class="sch" data-agent-id=2>Agent 2</div>
<div data-agentid="2" data-color="10">10</div>
<div data-agentid="2" data-color="20">20</div>
There is no selector that works off an array. So you would need to make a comma separated value
var selector = $('[data-color="30"]').map(function() {
return '[data-agent-id="' + $(this).data("agentid") + '"]';
}).get().join(',');
$(selector).hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-agentid="1" data-color="30"></div>
<div data-agentid="2" data-color="20"></div>
<div data-agentid="3" data-color="30"></div>
<div data-agent-id="1">1-1</div>
<div data-agent-id="2">2-1</div>
<div data-agent-id="3">3-1</div>
<div data-agent-id="1">1-2</div>
<div data-agent-id="2">2-2</div>
<div data-agent-id="3">3-2</div>
<div data-agent-id="1">1-3</div>
<div data-agent-id="2">2-3</div>
<div data-agent-id="3">3-3</div>
Other option is to use filter()
var ids = $('[data-color="30"]').map(function() {
return $(this).data('agentid');
}).get();
$('[data-agent-id]')
.filter(function () {
return ids.includes($(this).data('agent-id'));
})
.hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-agentid="1" data-color="30"></div>
<div data-agentid="2" data-color="20"></div>
<div data-agentid="3" data-color="30"></div>
<div data-agent-id="1">1-1</div>
<div data-agent-id="2">2-1</div>
<div data-agent-id="3">3-1</div>
<div data-agent-id="1">1-2</div>
<div data-agent-id="2">2-2</div>
<div data-agent-id="3">3-2</div>
<div data-agent-id="1">1-3</div>
<div data-agent-id="2">2-3</div>
<div data-agent-id="3">3-3</div>
Or just select in a loop
$('[data-color="30"]').each(function() {
var id = $(this).data('agentid');
$('[data-agent-id="' + id + '"]').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-agentid="1" data-color="30"></div>
<div data-agentid="2" data-color="20"></div>
<div data-agentid="3" data-color="30"></div>
<div data-agent-id="1">1-1</div>
<div data-agent-id="2">2-1</div>
<div data-agent-id="3">3-1</div>
<div data-agent-id="1">1-2</div>
<div data-agent-id="2">2-2</div>
<div data-agent-id="3">3-2</div>
<div data-agent-id="1">1-3</div>
<div data-agent-id="2">2-3</div>
<div data-agent-id="3">3-3</div>
Plain and simple in vanilla javascript:
document.querySelectorAll('[data-color="30"]').forEach(function(item) {
item.style.display = "none";
});
<div data-agentid="1" data-color="30">Test30</div>
<div data-agentid="2" data-color="20">Test20</div>
<div data-agentid="1" data-color="30">Test30</div>
<div data-agentid="2" data-color="20">Test20</div>
<div data-agentid="1" data-color="30">Test30</div>
<div data-agentid="2" data-color="20">Test20</div>
<div data-agentid="1" data-color="30">Test30</div>

get ALL id's of children elements

How do I get an array or something similar with ALL the id's of elements to a certain div?
Let's say I have someting like this:
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
I would then like an array that look's something like this
parent-div [
0: "div-no-1",
1: "div-no-2",
2: "div-no-3",
3: "div-no-3"
];
I've tried this...
$("#parent-div > div").attr("id");
...but it only gives me the first childs id, e.g. div-no-1. I want ALL of them
An alternative to Jack Bashford's solution using $.map:
const divIds = $.map($('#parent-div > div'), div => div.id);
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Or, using .map and .get:
const divIds = $('#parent-div > div').map((i, div) => div.id).get();
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Use jQuery's each and push the id to the array:
var parentDiv = [];
$("#parent-div > div").each((index, elem) => {
parentDiv.push(elem.id);
});
console.log(parentDiv);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
If you want to do it in pure JavaScript, you can just get the children of the parent element and then loop over the result and push the ids into an array.
var children = document.getElementById("parent-div").children;
var idArr = [];
for (var i = 0; i < children.length; i++) {
idArr.push(children[i].id);
}
console.log(idArr);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
This can be done in plain JavaScript using document.querySelectorAll('#paren-div > div') followed by a map() and some destructuring to get the id.
const ids = [...document.querySelectorAll('#parent-div > div')].map(({ id }) => id);
console.log(ids);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Give map a try
var arr = jQuery.map($("#parent-div").children(), function (d) {
return $(d).attr("id");
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can use .querySelectorAll() with Descendant combinator
Descendant combinator The (space) combinator selects nodes that are
descendants of the first element. Syntax: A B
"#parent-id [id]" to match all child nodes having an id attribute, spread syntax to convert NodeList to Array and Array.prototype.map()
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div></div>
<div class="div-no-2-6-6"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
text
</div>
<script>
let ids = [...document.querySelectorAll("#parent-div [id]")].map(({id}) => id);
console.log(ids);
</script>
The without jquery solution :
const elements = [...document.querySelectorAll('#parent-div *[id]')];
console.log(elements.map(({ id }) => id));
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can try this:
// Make an empty arary to push ids into
var arrayOfIds = [];
// Select parent element
var parentElement = document.querySelector('#parent-div');
// Select child elements
var childElements = parentElement.querySelectorAll("div");
// Push the id attribute of every child element
// Into he previousely created array
for (var i = 0; i < childElements.length; i++) {
arrayOfIds.push(childElements[i].getAttribute("id"));
}
console.log(arrayOfIds);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can use .getAttribute("class") to get the CSS classes of all the elements, or any other attribute, by the same logic.
var ids = [];
$("#parent-div > div").each(function( index ) {
ids.push($(this).attr('id'));
});

How do I find each child that comes after the body element, and get the html of the element with a certain class within it

That might sound a little confusing, but basically I have some html that looks like this (which is dynamically created)
<body>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
</body>
And I want to create an array of objects which includes the unique id of the component and the raw HTML within the element with class name "wantThis" (it will always be called "wantThis"), so the array would look like
[{
id: "465a496s5498",
html: "<div class='wantThisHTML'>Hello!<p>I'm another element!</p></div>"
},{
id: "683fg5865448",
html: "<div class='wantThisHTML'>Wow!</div>"
},{
id: "247487294js5",
html: "<div class='wantThisHTML'>Haha!</div>"
}]
As for what i've tried, I split up the elements into an array using var elements = $(body).children, and I know to get the HTML within an element using $(.wantThis).html(), but how can I get the id and the HTML from each of the elements I obtain from the children?
Also, within the wantThis element there may me multiple elements, will $(.wantThis).html() get the raw HTML of ALL the children?
There you go.
var data = $('> .component', document.body).map(function(component) {
return {
id: this.id,
html: $(this).find('.wantThisHTML').html()
}
})
.toArray();
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!
<p>I'm another element!</p>
</div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
ONE approach to this is....
Select the Nodes (elements) using "querySelectorAll"
let nodeListOfComponentElements = document.querySelectorAll('.component')
This will get you a NodeList. NodeList
You can turn that into an array of Nodes by:
let nodeArray = [].slice.call(nodeListOfComponentElements) SO-Post
Then, using that array of nodes. You can 'map' it to the structure you want.
let result = nodeArray.map(function(item, index) {
let targetElement = item.querySelector('.wantThisHTML')
return {
id: item.id,
html: targetElement.innerHTML
}
})
note: each "item" is an element/node and the method querySelector can be used to select children of that element. I'm targeting the class you mentioned. Then it's just a matter of returning an object for each iteration that the map function executes. You pick the keys and values that the map function returns. Here I'm setting the id key to the id of the element, and the html key to the "innerHTML" of the target child element within each main element.
The resulting structure is as follows:
(3) [{…}, {…}, {…}]
0: {id: "465a496s5498", html: "Hello!<p>I'm another element!</p>"}
1: {id: "683fg5865448", html: "Wow!"}
2: {id: "247487294js5", html: "Haha!"}
length: 3
CodePen: https://codepen.io/nstanard/pen/exOJLw
Don't forget to upvote and approve my answer it helps!
Thanks
To make sure the .component has wanted '.wantThis' child.
var data = $('.wantThis').map(function() {
return {
id: $(this).parents('.component').attr('id'),
html: $(this).html()
}
});
console.log(data);
var data = $('.wantThis').map(function() {
return {
id: $(this).parents('.component').attr('id'),
html: $(this).html()
}
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
alert(elem); // DOM-element with id="elem"
alert(window.elem); // accessing global variable like this also works
// for elem-content things are a bit more complex
// that has a dash inside, so it can't be a variable name
alert(window['elem-content']); // ...but accessible using square brackets [...]
</script>
reference: https://javascript.info/searching-elements-dom

Convert rows of Div values into an array with jQuery

Example:
I have a variable amount of rows, each with 3 divs with classes like so:
<div class="row>
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row>
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row>
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
How can I use jQuery to gather them into an associative array that I'll be passing to php to INSERT into a database table?
You can use map to loop thru the .row div. Use reduce to group the inner divs into a js object.
var result = $('.row').map(function() {
return $(this).find('div').toArray().reduce(function(c, v) {
c[$(v).attr('class')] = $(v).text();
return c;
}, {});
}).get();
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row">
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row">
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
To select each all the div with the class row use this
var rows=$('div.row');
To loop through it use this
var array=[];
for(var i=0;i <rows.length;i++){
$.each(rows,function(){
var children=this.children('div');
$.each(children,function(){
var index=this.attr('class');
var value=this.text();
array[i][index]=value;
});
});
}
console.log(array);

Array sort before looping not keep the array sort

I have this code who simply create a array with html element and loop for parse the sort array.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[style + '-' + index ] = $(this).find('.element');
});
arrElementStyle.sort();
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
When I parse the html the result is not sort?(I want sort by style of music) Why? Want should I do.
in your code you declared arrElementStyle as an array, but later you used it as an associative array for inserting data. So it is better to declare arrElementStyle as an object for this.
Here is an example demo of what I think you wanted to achieve with the help of sort() for sorting the objects keys:
$('document').ready(function() {
var arrElementStyle = {}; // declare arrEleemntStyle as object
$('.bands-alphabetique [id*="band-style-"]').each(function(index) {
var style = $(this).attr('id').split('-')[2];
// push into object of key <style>-<index> the elements
arrElementStyle[style + '-' + index] = $(this).find('.element');
});
// get the keys of arrElementStyle for sorting
var keys = Object.keys(arrElementStyle),
i, len = keys.length;
console.log('before = ', keys);
keys.sort(); // sort the object keys
console.log('after = ', keys);
$('.bands-alphabetique').hide();
// iterate the sorted keys and append it
for (i = 0; i < len; i++) {
var k = keys[i];
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[k]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>
Issue is you're trying to sort an object.. not an array. So let's use an object and sort it's keys.
$('document').ready(function() {
// here's the issue I was saying about
var elements = {};
$('.bands-alphabetique').hide().find('[id*="band-style-"]').each( function( index ) {
elements[ $(this).attr('id').split('-')[2] + '-' + index ] = $(this).find('.element');
});
var styles = Object.keys(elements);
styles.sort();
styles.forEach(function(style) {
$('.large-centered.col-md-12.clearfix').append(elements[style]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
</div>
</div>
The problem is that you're not sorting an array. You have an object with different properties (style + '-' + index).
In other words, associative array does not exists in Javascript. What you really had was an object arrElementStyle with many properties.
$('document').ready(function(){
var arrElementStyle = [];
$('.bands-alphabetique [id*="band-style-"]').each(function(index){
var style = $(this).attr('id').split('-')[2];
arrElementStyle[index] = $(this).find('.element');
arrElementStyle[index].bandStyle = $(this).find('.band-style-title')[0].innerHTML;
});
arrElementStyle.sort(function(elementA, elementB){
return elementA.bandStyle > elementB.bandStyle;
});
$('.bands-alphabetique').hide();
for(style in arrElementStyle){
$('.large-centered.col-md-12.clearfix').append(arrElementStyle[style]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-centered col-md-12 clearfix">
<div class="bands-alphabetique">
<div class="col-md-3" id="band-style-rock">
<div class="element">
<h1 class="band-style-title">Rock</h1>
Fiction In Motion
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Pop</h1>
Marianas Trench
</div>
</div>
<div class="col-md-3" id="band-style-pop">
<div class="element">
<h1 class="band-style-title">Alternatif</h1>
Anberlin
</div>
</div>
</div>
</div>

Categories

Resources