Reputation: 1003
I am attempting to retrieve the text of an a element of li element that I created via javascript. Here is the code I used to create:
function myFunction(search) {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('delegateNameInput');
filter = input.value.toUpperCase();
ul = document.getElementById("nameList");
li = ul.getElementsByTagName('li');
data = ['test1', 'test2', 'test3'];
for (i = 0; i < data.length; i++) {
var lineItem = document.createElement("li");
lineItem.setAttribute('onClick', 'setName(this)');
var link = document.createElement("a");
link.appendChild(document.createTextNode("test2"));
lineItem.appendChild(link);
ul.appendChild(lineItem);
}
}
How would I get the text from the a element?
Upvotes: 0
Views: 67
Reputation: 19301
The way it's written, the anchor element is the first child of the LI element created, and is pointed to by the firstChild
property of the LI element.
Alternatively you could locate the A element as the first entry in the children
property of the LI node in the DOM.
For the purposes of this demo I've set the text within list items to different data array entries, declared data
, and ignored unused variables input, filter
and li
:
"use strict";
function myFunction(search) {
// Declare variables
var input, filter, ul, li, a, i, data;
input = document.getElementById('delegateNameInput');
filter = input.value.toUpperCase();
ul = document.getElementById("nameList");
li = ul.getElementsByTagName('li');
data = ['test1', 'test2', 'test3'];
for (i = 0; i < data.length; i++) {
var lineItem = document.createElement("li");
lineItem.setAttribute('onClick', 'setName(this)');
var link = document.createElement("a");
link.appendChild(document.createTextNode(data[i]));
lineItem.appendChild(link);
ul.appendChild(lineItem);
}
}
function setName( lineItem) {
console.log("setName>lineItem>Anchor>link text = '" + lineItem.firstChild.textContent + "'");
console.log("(using children: '" + lineItem.children[0].textContent + "')");
}
myFunction(null);
<input type="text" id="delegateNameInput" placeholder="delegateNameInput">
<ul id="nameList">
</ul>
(Click a list item to see console message)
firstChild
is inherited from the node interface
children
is inherited from the ParentNode mixin and is a live HTMLCollection.
Upvotes: 1