Lets break the task down into several steps:
- Get a handle to all of our links (
document.querySelectorAll
)
learn how to get the current text of an a
tag (childNode[0].nodeValue
)
put it all together (Array.from
, Array.map
)
Get a handle to all of our links:
we will use document.querySelectorAll
to get list of all nodes that match our selector. here I'm just going to use the selector a
, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue
for each one. We could probably get away with just using the nodeValue
of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map
to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map
we will have to have an array, and document.querySelectorAll
returns a NodeList
instead. So to convert it over we will use Array.from
to turn our NodeList
into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
<a href="1">this is text</a>
<a href="2">this is some more text</a>
Use ['.contains(myVar)'](https://api.jquery.com/contains-selector/) in your selector for 'a' tags. –
do you mean if '123的文本'會產生值爲'123'的var名爲'example1',依此類推? –