Using document.getElementsByClassName("span3 pickItem").outerHTML)
I set a variable htmlData to contain:
<div itemscope="" >
<p itemprop="name" >
<a href="/user/view?id=4943">
<span>John Doe</span>
<br />
<span>'Arizona'</span>
<br />
<span>'Student'</span>
</a>
</p>
</div>
How can I pick each value from the span tag and console.log them as such:
console.log(...span[0])
output: John Doe
console.log(...span[1])
output: Arizona
console.log(...span[2])
output: Student
CodePudding user response:
Could do something like this
let namesArr = [];
let name = document.querySelectorAll("span");
name.forEach(function(names) {
namesArr.push(names.innerHTML);//Stores all names in array so you can access later
});
console.log(namesArr[0]);
console.log(namesArr[1]);
console.log(namesArr[2]);
CodePudding user response:
Something like this should work:
// console log all names
const items = document.querySelectorAll('div.pickItem span')
items.forEach(item => {
console.log(item.innerText)
})
// console each from array index
console.log(items[0].innerText)
console.log(items[1].innerText)
console.log(items[2].innerText)
CodePudding user response:
let spans = document.getElementsByTagName('span');
console.log(spans[0].innerHTML); //'Joe Doe'
CodePudding user response:
You don't even need the
htmlData
variable because the DOM elements already exist. If you want to learn about parsing a string of HTML (this is what yourhtmlData
variable has in it) into DOM elements, you can reivewDOMParser.parseFromString()
- Web APIs | MDN.
- Select the
a
nchor - Select its child
span
s and map theirtextContent
properties
function getTextFromSpan (span) {
// Just return the text as-is:
// return span.textContent?.trim() ?? '';
// Or, you can also remove the single quotes from the text value if they exist:
const text = span.textContent?.trim() ?? '';
const singleQuote = `'`;
const hasQuotes = text.startsWith(singleQuote) && text.endsWith(singleQuote);
return hasQuotes ? text.slice(1, -1) : text;
}
const anchor = document.querySelector('div.span3.pickItem > p.name > a');
const spanTexts = [...anchor.querySelectorAll(':scope > span')].map(getTextFromSpan);
for (const text of spanTexts) {
console.log(text);
}
<div itemscope="" >
<p itemprop="name" >
<a href="/user/view?id=4943">
<span>John Doe</span>
<br />
<span>'Arizona'</span>
<br />
<span>'Student'</span>
</a>
</p>
</div>