Bar
Baz
I would like...">

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
source share
4 answers
var text = [];
document.querySelectorAll(".foo").forEach(function(e){
    text.push(e.textContent);
});
+3
source

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 .

ES5 version :

var elements = document.querySelectorAll('.foo')

var texts = []

elements.forEach(function(element) {
    texts.push(element.innerText.toLowerCase())
})

console.log(texts)
+1
source

, , -, ( !).

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
source

This question has a very simple answer: you should use the function d3.selectAll()and text, as shown below:

var array=[];
d3.selectAll(".foo").each(function(d,i){
   array.push(d3.select(this).text());
});
0
source

Source: https://habr.com/ru/post/1666857/


All Articles