Adding class to elements in a loop processing AJAX response - javascript

AJAX request returns XML containing such nodes:
<root>
<directory><li onclick=myFunc()>stuff</li></directory>
...
</root>
Then code processes it like this:
var folderContent = '';
var data = xhttp.responseXML;
var folders = data.getElementsByTagName("directory");
for (var i = 0; i < folders.length; i++) {
folderContent += folders[i].childNodes[0].nodeValue;
}
document.getElementById('folders').innerHTML = folderContent;
I want to add to every list item one class (identical to every element). How should I do that using JavaScript?
Thanks.

You can use setAttribute to set add(or change) an attribute. Also I notice you are calling nodeValue on an element node which is always undefined.
If your aim is to append the li node to folderContent then you will have to serialize it to string before appending to folderContent.
var folderContent = '';
var data = xhttp.responseXML;
var folders = data.getElementsByTagName("directory");
var serializer = new XMLSerializer();
var node;
for (var i = 0; i < folders.length; i++) {
node=folders[i].childNodes[0];
node.setAttribute('class', 'your-class')//sets class attribute to li node
folderContent += serializer.serializeToString(node);//serialize li node before and appends it to folderContent
}
Hope it helps.

It worked:
var ul = document.createElement('ul');
var li;
for (var i = 0; i < folders.length; i++) {
li = document.createElement('li');
li.innerHTML = folders[i].childNodes[0].nodeValue;
li.setAttribute('onclick', 'Toggle(this, true)');
li.setAttribute('class', 'first-level');
ul.appendChild(li);
}
document.getElementById('folders').innerHTML = ul.innerHTML;

Related

create element and then insert html tag

I have a json data and I'm looping inside of it and create a set of li's in every (.searchinput-sub)
var searchinput_sub = document.querySelectorAll(".searchinput-sub");
for (var i = 0, max = searchinput_sub.length; i < max; i++) {
var jsonResData = JSON.parse(e.data);
for(var l=0;l<jsonResData.length;l++){
//create a li element
var newEl = document.createElement('li');
newEl.innerHtml ='test';
searchinput_sub[i].querySelector('.resultsHolder').appendChild(newEl);
}
}
but this part
newEl.innerHtml ='test';
is not working, like only li tags was added. Any ideas, help please?
It will be innerHTML not innerHtml:
newEl.innerHTML ='test';

Delete unordered list in HTML with Javascript DOM

Basically, the task I needed to perform is to delete the whole "agent" array by using the removeChild() function, but it needs the <ul> id, according to what I read [here][1].
After that, I need to replace the "agent" array with "freshagent" array and display it in an unordered list.
My problem is that I can't set the id for "ul" because I used the createElement() function.
Thus, I can't remove the "agent" array.
//old code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
</div>
<script>
var agents = [
"Dion" ,
"Elisa" ,
"Selena" ,
"Shauna" ,
"Rodger"
];
var freshAgents = [
"Gray",
"Shivani",
"Brainne",
"Jason",
"FChad"
];
var i = 0;
var ul = document.createElement('ul');
ul.setAttribute("id","aList");
for (i in agents){
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
rList = document.getElementById("aList");
if (rList.hasChildNodes()){
for(i in agents){
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (i in finalList){
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
document.getElementById("wrapper").appendChild(ul);
</script>
</body>
</html>
//new code(working)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
</div>
<script>
var agents = ["Dion" ,"Elisa" , "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason","FChad"];
var i = 0;
var ul = document.createElement('ul');
for (i in agents){
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
var rList = document.getElementById("wrapper").appendChild(ul);
do{
rList.removeChild(rList.childNodes[0]);
}while(rList.hasChildNodes())
for (i in freshAgents){
var list = document.createElement('li');
list.appendChild(document.createTextNode(freshAgents[i]));
ul.appendChild(list);
}
</script>
</body>
</html>
Seems like you are going about it a really long way. I have tweaked your code somewhat to make it do what I think you are asking. I would do something different but it seems clear from your question that this is the way you want it.
var agents = ["Dion", "Elisa", "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason", "FChad"];
var ul = document.createElement('ul');
ul.id = "aList";// give it an ID
for (var i = 0; i < agents.length; i++) {
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
document.getElementById("wrapper")
.appendChild(ul);
rList = document.getElementById("aList");//this is the same as ul variable declared above
if (rList.hasChildNodes()) {
console.log(rList.childNodes);//lists the <LI>...<LI> nodes
for (var i = 0; i < rList.childNodes.length; i++) {//Loop through the nodes not your agent array
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (var i = 0; i < finalList.length; i++) {
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
Working fiddle here
I can't really understand much of your question, but based on this
Problem: I can't set id for "ul" because of using createelement function. I can't remove "agent" array.
I assume you want to add an id to an element that was created with document.createElement(). You can do that like so:
var el = document.createElement('div');
el.id = 'exampleID';
First of all, please input your code in a neat and legible manner, so that it is readable by everyone. I've formatted your code to the following:
var agents = ["Dion", "Elisa", "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason", "FChad"];
var i = 0;
var ul = document.createElement('ul');
ul.setAttribute("id", "aList");
for (i in agents) {
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list); }
rList = document.getElementById("aList");
if (rList.hasChildNodes()) {
for (i in agents) {
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (i in finalList) {
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
document.getElementById("wrapper").appendChild(ul);
Another tip: since you're referring your HTML, it's recommended that you provide that code as well. Again, it's not a necessity, but just etiquette.
As for setting the id, use:
var example = document.createElement('ul');
example.id = 'example_ID';

Appending a link to a li element

I am trying to append an a link to the list items but I am struggling figuring out how to get the a link with the textnode.
So basically I want something along the lines of
<li>Bumble</li>
I have managed to get the li's outputting correctly, I just don't understand how I have the a element as part of the output too.
Here is all the code
//Process the JSON data
function processResponse (){
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response[1])
//Grab suggestions div from DOM
var suggestions = document.getElementById('suggestions');
//Create new element UL
var list = document.createElement('UL');
//Create new elements for li's
var newLi, newText ;
//For all the text nodes
var textNodes = [];
//For all the li's
var liList = [];
//For all the links
var links = [];
//For loop to add and append all suggestions
for (var i = 0; i < response[1].length; i++) {
links[i] = document.createElement('a');
var setHTML = response[1][i].replace(/\s/g, '_');
var link = 'http://en.wikipedia.org/wiki/'+setHTML;
links[i].href = link;
//Create new text node with the response from api
textNodes[i] = document.createTextNode(response[1][i]);
//Create a new element 'li' into array
liList[i] = document.createElement('li')
//Append the response(textnode) to the li in the array
liList[i].appendChild(textNodes[i]);
//Append the li to the UL
list.appendChild(liList[i]);
}
console.log(links);
//Append the UL to the suggestions DIV
suggestions.appendChild(list);
} else {
alert('There was a problem with the request');
}
}
}
You create the a elements, but you never put them in the li elements. Currently, your code does
//Append the response(textnode) to the li in the array
liList[i].appendChild(textNodes[i]);
Maybe you wanted
//Append the response(textnode) to the a in the array
links[i].appendChild(textNodes[i]);
//Append the a to the li in the array
liList[i].appendChild(links[i]);
for (var i = 0; i < response[1].length; i++) {
links[i] = document.createElement('a');
var setHTML = response[1][i].replace(/\s/g, '_');
var link = 'http://en.wikipedia.org/wiki/'+setHTML;
links[i].href = link;
links[i].text = response[1][i];
//Create new text node with the response from api
//textNodes[i] = document.createTextNode(response[1][i]);
//Create a new element 'li' into array
liList[i] = document.createElement('li')
//Append the response(textnode) to the li in the array
liList[i].appendChild(links[i]);
//Append the li to the UL
list.appendChild(liList[i]);
}
You're close. Append the text node to the link, and append that to the li:
textNodes[i] = document.createTextNode(response[1][i]);
links[i].appendChild(textNodes[i]);
liList[i] = document.createElement('li')
liList[i].appendChild(links[i]);
list.appendChild(liList[i]);

Get the source of images from table cell

I am trying to get to the img.src of these table cells, but am going wrong somewhere.
var cell = newTable.rows.cells;
var content = newTable.getElementsByTagName('img');
var nodeArray = [];
for(var i = 0; i < content.length; ++i)
{
nodeArray[i] = content[i];
}
var listThem = $(this).attr('src');
console.log(listThem);
Use this :
var content = newTable.getElementsByTagName('img');
for(var i = 0; i < content.length; i += 1) {
var source = content[i]['src'];
//do something
}
getElementsByTagName() returns an array of dom elements.
To access the "src" attribute of a dom element, you can do this : element.src or element['src'];
source will contain the image source.

How to add DOM Element in for loop

How can I create new Element each time when (i) will be incremented:
for(int i = 0; i < 10; i++)
{
Element child = doc.createElement("xxx");
root.setAttribute("x", i * "xx");
doc.appendChild(child);
}
Using pure js
var div = document.getElementById("main");
for (var i = 0; i < 10; i++) {
var span = document.createElement("span");
span.setAttribute("class", "new");
span.innerHTML = "span" + i;
div.appendChild(span);
}​
HTML
​<div id="main"></div>​​​​​​​
Working example.
Cheers!!
Using java
Element child = null;
for(int i = 0; i < 10; i++)
{
child = doc.createElement("xxx" + i);//you can write a method with int parameter to get element name from somewhere else
doc.appendChild(child);
}
I hope this is what you wanted, by the way for text nodes you should use doc.createTextNode("A")

Categories

Resources