document.querySelectorAll get innerText of ALL selected elements at once pure javascript

℡╲_俬逩灬. 提交于 2020-01-01 03:32:12

问题


I want to get all innerText of a whole column of a very long html table (random length). I'm using this code:

var tbEls = document.querySelectorAll('#tBodyID tr td:nth-child(cidx)');

Where cidx = the column index I want to extract content from.

But such code extracts all the td elements (with the innerText inside them of course). But it doesn't extract directly all the innerText inside them. Cause of this I have to reprocess the returned tdEls array with a for loop to extract from each tbEls[i] element its own innerText. It works but...

My question is:

In pure JS (no external libraries or frameworks) is it possible to use a more direct approach improving some way just and only the querySelectorAll parameter ('#tBodyID tr td:nth-child(cidx)') to get directly all the td elements innerText at once and in just one javascript statement and without the need of reprocessing the returned array with the for loop or anything else?

In other words is there a some kind of innerText selector that can be used to get them all at once without any kind of extra loop?

No problem at all if it is not recognized by old browsers, I'm sorry for them.

What I hope to achieve is something like:

var arrTblColInnerText = document.querySelectorAll('#tBodyID tr td:nth-child(cidx):alltd:innerText');

I want to get an array similar to:

0: value from column cidx cell 0
1: value from column cidx cell 1
2: value from column cidx cell 2
3: value from column cidx cell 3
...
n: value from column cidx cell n

Thanks in advance.


回答1:


The easiest way I found was to convert the nodeList to an array first then use a map:

var nodes = document.querySelectorAll("h3 em");
var list = [].slice.call(nodes);
var innertext = list.map(function(e) { return e.innerText; }).join("\n");


来源:https://stackoverflow.com/questions/38774726/document-queryselectorall-get-innertext-of-all-selected-elements-at-once-pure-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!