Get innerHTML from a selection
I have the following divon an HTML page:
<div class="foo">Bar</div>
<div class="foo">Baz</div>
I would like to get an array with text contained in two divs:
['Bar', 'Baz']
I can do this with help d3.nodes, but it seems a bit awkward. Is there a smarter way?
d3.selectAll(".foo").nodes().map(function(d) { return d.innerHTML; });
The answer may be pure Javascript, of course!
+4
4 answers
This is entirely possible using vanilla JavaScript (ES6):
let elements = document.querySelectorAll('.foo')
let texts = []
for(let element of elements) {
texts.push(element.innerText.toLowerCase())
}
console.log(texts)
This infers ["bar", "baz"], as can be seen here .
var elements = document.querySelectorAll('.foo')
var texts = []
elements.forEach(function(element) {
texts.push(element.innerText.toLowerCase())
})
console.log(texts)
+1
, , -, ( !).
selection.nodes(), DOM, :
var fooDivs = d3.selectAll(".foo").nodes()
Now you can use this to get any HTML / CSS property your heart desires using native JavaScript Array.map:
fooDivs.map(function(d) {
return d.innerHTML;
});
Or, for those who love one-liners:
d3.selectAll(".foo").nodes().map(function(d) { return d.innerHTML; });
+1