How can I go through on elements which contains same class and take a part of the div?
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >9852183</div>
<div ><span >Due at 12:00</span></div>
</div>
I have 3 divs with class "Selected". I count it with the next code:
var po_list_number = document.querySelectorAll('.Selected').length;
alert(po_list_number);
My question is, how can I see if there is duplicated div? (The apptId content if same) If there is, count just once and take the time once as well.
So I need to create a second list which containts just time but never duplicate.
CodePudding user response:
Put the contents of the DIVs in a Set
and get the size of the set. Since sets can't have duplicate values, this is the number of unique strings.
const apptid_divs = [...document.querySelectorAll('.Selected .apptId')];
const apptid_set = new Set(apptid_divs.map(div => div.textContent.trim()))
console.log(apptid_set.size);
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >9852183</div>
<div ><span >Due at 12:00</span></div>
</div>
CodePudding user response:
The accepted answer doesn't retrieve the time and create a unique list as requested by the original question.
Here's the correct JavaScript code that outputs a uniquePoListCount
count and a key:value uniquePoList
object of unique apptId details as requested.
// Select all .Selected elements
let poList = document.querySelectorAll('.Selected')
// List the element objects in the original poList array
poList = Object.entries(poList)
// Define variables to avoid declarations in a loop
let poListEntry = ''
let poListEntryId = ''
let uniquePoList = {}
let uniquePoListCount = 0
// Loop through poList entries
for (let poListKey in poList) {
// Set the poListEntry to a variable
poListEntry = poList[poListKey][1]
// Set the apptId to a variable
poListEntryId = poListEntry.querySelector('.apptId').innerText
if (typeof uniquePoList[poListEntryId] === 'undefined') {
// Populate uniquePoList with [{apptId: details}] after verifying uniqueness of apptId
uniquePoList[poListEntryId] = poListEntry.querySelector('.details .timestamp').innerText
// Increment count of unique apptIds
uniquePoListCount
}
}
console.log("Count of unique appointments")
console.log(uniquePoListCount)
console.log("List of unique appointments")
console.log(uniquePoList)
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >4320573</div>
<div ><span >Due at 09:00</span></div>
</div>
<div >This Is selected
<div >9852183</div>
<div ><span >Due at 12:00</span></div>
</div>