I am having a list of email I need to push those email in object list but each email I kept on a separate p tag and each p tag has dynamic id. Below is the code I am using
<div >
<p id="emailrecord1">[email protected]<span><a href="#" onclick="recremove(this);" ><i ></i></a></span></p>
<p id="emailrecord2">[email protected]<span><a href="#" onclick="recremove(this);" ><i ></i></a></span></p>
</div>
var result = [];
function storeResult() {
result.push({
email: document.querySelector('.show-rec').innerText,
});
console.log(result);
}
I want each email as a separate object.
CodePudding user response:
You need to loop through each <p>
tag and extract its .innerText
property:
var result = [];
function storeResult() {
document.querySelectorAll('.show-rec p').forEach(function(elmt){
result.push({
email: elmt.innerText
});
})
console.log(result);
}
storeResult()
<div >
<p id="emailrecord1">[email protected]<span><a href="#" onclick="recremove(this);" ><i ></i></a></span></p>
<p id="emailrecord2">[email protected]<span><a href="#" onclick="recremove(this);" ><i ></i></a></span></p>
</div>
CodePudding user response:
Pure function sample:
var result = [...document.querySelector('.show-rec').childNodes]
.filter(e => e.nodeType === Node.ELEMENT_NODE)
.map(e => ({ email: e.innerText }));