LondonRob
LondonRob

Reputation: 78713

Get innerHTML from selection

I have the following divs in an HTML page:

<div class="foo">Bar</div>
<div class="foo">Baz</div>

I'd like to get an array with the text contained in the two divs:

['Bar', 'Baz']

I can do this using d3.nodes but it seems a bit clunky. Is there a smarter way?

d3.selectAll(".foo").nodes().map(function(d) { return d.innerHTML; });

The answer could be pure Javascript, of course!

Upvotes: 6

Views: 2896

Answers (5)

In pure JS we can achieve this pretty easily by using an array map, which is conveniently built into the Array.from function:

const text = Array.from(
  document.querySelectorAll(".foo"),
  e => e.textContent
);

console.log(text);
<div class="foo">Bar</div>
<div class="foo">Baz</div>

Of course, this does require turning the query's static NodeList (which supports forEach, but not map) into a real Array, but that's typically what you want anyway.

Upvotes: 1

LondonRob
LondonRob

Reputation: 78713

Given a few comments to the original post, this seems to be the slickest way (so far!).

Using selection.nodes() gets you access to the DOM elements behind the selection:

var fooDivs = d3.selectAll(".foo").nodes()

You can now use this to get any HTML/CSS property your heart desires, by using the 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; });

Upvotes: 3

MR Zamani
MR Zamani

Reputation: 1423

This question have very simple answer, you have to use d3.selectAll() and text function like below:

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

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

var text = [];
document.querySelectorAll(".foo").forEach(function(e){
    text.push(e.textContent);
});

Upvotes: 3

Bojangles
Bojangles

Reputation: 101473

This is quite easily possible with vanilla JavaScript (ES6):

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

let texts = []

for(let element of elements) {
    texts.push(element.innerText.toLowerCase())
}

console.log(texts)

This outputs ["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)

Upvotes: 1

Related Questions