How to add class to element created using document.createElement? - javascript

I have managed to add a class to the ul element but I can't get the syntax right to add classes to the li and a elements. Can anyone help please?
<script>
anchors.options.placement = 'left';
anchors.add('.entry-content h2');
generateTableOfContents(anchors.elements);
// External code for generating a simple dynamic Table of Contents
function generateTableOfContents(els) {
var anchoredElText,
anchoredElHref,
ul = document.createElement('UL');
ul.className = "uk-nav uk-nav-default";
document.getElementById('table-of-contents').appendChild(ul);
for (var i = 0; i < els.length; i++) {
anchoredElText = els[i].textContent;
anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
addNavItem(ul, anchoredElHref, anchoredElText);
}
}
function addNavItem(ul, href, text) {
var listItem = document.createElement('LI'),
anchorItem = document.createElement('A'),
textNode = document.createTextNode(text);
anchorItem.href = href;
ul.appendChild(listItem);
listItem.appendChild(anchorItem);
anchorItem.appendChild(textNode);
}
</script>

before append li tag in the ul you need add your class then append li tag to ul tag like this
var listItem = document.createElement('LI');
listItem.className = 'someClassName';
ul.appendChild(listItem);

Related

Use js to append an ul to an li

yeah you read it right i'm trying to append an ul element in an existing li element and create a sub list. I'm using code from codepen (https://codepen.io/Pestov/pen/AvQmxv) to make a genealogy tree and i would like to create dynamically the tree. For this, i have to create a sub ul element in a previously created li, then had two li to that sub ul.
----EDIT----
My problem is: HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
Js seems to think that my ul is my parent but in fact it's a new sub ul.
Here's my code:
<div class="tree" id="tree"></div>
function launchTree(){
var div = document.getElementById("tree");
var ul = document.createElement("ul");
var li = document.createElement("li");
var a = document.createElement("a");
//create the main ul element
ul.setAttribute("id", "main_ul");
div.appendChild(ul)
//put my first parent
li.setAttribute("id", "AC_Lila_li");
a.setAttribute("data-content", "AC Lila");
a.setAttribute("id", "AC_Lila_a");
ul.appendChild(li);
li.appendChild(a);
//create my sub ul to put childs !!!! here's the problem!!!
ul.setAttribute("id", "AC_Lila_ul");
li.appendChild(ul)
//create my first child
li.setAttribute("id", "Queen_Elisa_li");
a.setAttribute("data-content", "Queen Elisa");
a.setAttribute("id", "Queen_Elisa_a");
ul.appendChild(li);
li.appendChild(a);
//create my second child
li.setAttribute("id", "Wendy_li");
a.setAttribute("data-content", "Wendy");
a.setAttribute("id", "Wendy_a");
ul.appendChild(li);
li.appendChild(a);
}
I hope i'm clear of what i wanted to do and thanks for your help!
It was so simple, in fact, ul was always the same so i had to define my variables again. Here's the new code:
function debut(){
var div = document.getElementById("tree");
var ul = document.createElement("ul");
var li = document.createElement("li");
var a = document.createElement("a");
ul.setAttribute("id", "main_ul");
div.appendChild(ul)
li.setAttribute("id", "AC_Lila_li");
a.textContent = "AC Lila";
a.setAttribute("id", "AC_Lila_a");
ul.appendChild(li);
li.appendChild(a);
var ul = document.createElement("ul");
ul.setAttribute("id", "AC_Lila_ul");
li.appendChild(ul)
var li = document.createElement("li");
var a = document.createElement("a");
li.setAttribute("id", "Queen_Elisa_li");
a.setAttribute("onclick","descend_click();");
a.textContent = "Queen Elisa";
a.setAttribute("id", "Queen_Elisa_a");
ul.appendChild(li);
li.appendChild(a);
var li = document.createElement("li");
var a = document.createElement("a");
li.setAttribute("id", "Wendy_li");
a.setAttribute("onclick","descend_click();");
a.textContent = "Wendy";
a.setAttribute("id", "Wendy_a");
ul.appendChild(li);
li.appendChild(a);
}
A way to do that :
const
divTree = document.querySelector('#tree')
, infos =
[ { elmLI : { id:'AC_Lila_li' }, elmA: { id:'AC_Lila_a', 'data-content': 'AC Lila' } }
, { elmLI : { id:'Queen_Elisa_li' }, elmA: { id:'Queen_Elisa_a', 'data-content': 'Queen Elisa' } }
, { elmLI : { id:'Wendy_li' }, elmA: { id:'Wendy_a', 'data-content': 'Wendy' } }
];
// launchTree()
function launchTree()
{
let nvUL = divTree.appendChild( document.createElement('ul') )
nvUL.id = 'main_ul'
for (let { elmLI, elmA } of infos )
{
let
nvLI = nvUL.appendChild( document.createElement('li') )
, nvA = nvLI.appendChild( document.createElement('a') )
;
nvLI.id = elmLI.id
nvA.id = elmA.id
nvA.dataset.content = elmA['data-content']
nvA.textContent = '-----'
}
}

I want to add space between an li element i created using DOM selectors and the button element created along side it

How can i add space between the an li element created and the button element created?
function createListElement(){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
ul.appendChild(li);
input.value = "";
li.addEventListener("click", linecross);
}
jut add some margin left to button
function createListElement(){
var li = document.createElement("li");
var input =document.getElementsByTagName('input')[0];
var ul =document.getElementsByTagName('ul')[0];
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
ul.appendChild(li);
input.value = "";
li.addEventListener("click", linecross);
}
function linecross(){
console.log('linecross');
}
createListElement();
button{
margin-left:200px;}
<input value=5/>
<ul></ul>
Using the style property you can solve it in css
function createListElement(){
var input = {value:'random text'};
var ul = document.querySelector('ul');
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
Delete.style.marginLeft = '10px';
ul.appendChild(li);
input.value = "";
li.addEventListener("click", function(){});
}
createListElement()
<html>
<head></head>
<body>
<ul></ul>
</body>
</html>

I need to put my LI array element into a UL but I cant

HERE IS THE CODE:
I need to do a couple of things but I am pretty new coding :S.
First I need to format the li elements I am loading into the array into a UL. them I need also to create a loop where I can print those 20 array elements repeating them to display 2300 elements. Thanks :)
var _objetsOfArray = new Array();
var darFormato = function (numero){
var numero = document.createElement("li");
var contenido = document.createTextNode(i);
numero.appendChild(contenido);
document.body.insertBefore(numero);
}
for (i = 0; _objetsOfArray.length < 20; i++ ){
_objetsOfArray.push (i);
darFormato(i);
};
This resolved it for you.
http://jsfiddle.net/t4Vec/
var count = 2300;
while (count){
var _objectsOfArray = [],
ul = document.createElement("ul");
for (var i = 0; i < 20; i++){
var item = document.createElement("li");
item.innerText = i;
_objectsOfArray.push(item);
ul.appendChild(_objectsOfArray[i]);
count --;
}
//do something with UL
document.body.appendChild(ul);
}
If you have a precreated list, you could use innerHTML and parse it accordingly.
My sample just prints a ul with 20 Li elements with the text node set to the index of the node
Edit: New Fiddle: http://jsfiddle.net/t4Vec/1/
I use this on a page to generate some dynamic links:
<ul id="list">
</ul>
and here is the script
var myData = [
"item1",
"item2"
]
function createItems()
{
var ul = document.getElementById("list");
for (var i = 0; i < myData.length; i++)
{
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "http://stackoverflow.com/search?tab=newest&pagesize=30&q=" + myData[i].toLowerCase();
a.target = "_blank";
a.innerHTML = myData[i];
li.appendChild(a);
ul.appendChild(li);
}
}
createItems();
where I changed the hrefs to SO :)
I hope taking a look will help you

How to add a document fragement to a div

I have this simple code. I need to add this ul html list to "my-div", but with this code I cannot add it. Any idea what is wrong?
Would be possible add the fragmentusing jquery?
this.renderMenuTop = function() {
var menu, f, ul;
menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
f = document.createDocumentFragment();
ul = document.createElement('ul');
for (var i = 0; i < menu.length; i++) {
var li = document.createElement('li')
li.id = menu[i];
ul.appendChild(li);
}
document.getElementById("my-div").appendChild(f);
//$(this.elmMenuTop).append(f);
}
You never add any elements to your document fragment. Add this after your for loop:
f.appendChild(ul);
Another option is to just dump the document fragment altogether and just:
document.getElementById("my-div").appendChild(ul);
// ^^ Change from f to ul
You never put anything in f. But why do you even have a document fragment?
this.renderMenuTop = function() {
var menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
var ul = document.createElement('ul');
for (var i = 0; i < menu.length; i++) {
var li = document.createElement('li')
li.id = menu[i];
ul.appendChild(li);
}
document.getElementById("my-div").appendChild(ul);
//$(this.elmMenuTop).append(f);
};
If you need to append it to two different things, a document fragment won’t help.
Where do you add the list to the fragment? You'd need to add
f.appendChild(ul);
before adding it to the div. Alternatively, just add the list straight to the div without the fragment.
To answer the second part of your question, this is also possible with jQuery:
this.renderMenuTop = function() {
var menu = ['menu-actuality', 'menu-archive', 'menu-pdf', 'menu-pictures'];
var $ul = $('<ul></ul>');
for (var i = 0; i < menu.length; i++) {
$ul.append('<li>' + menu[i] + '</li>');
}
$('#my-div').append($ul);
}

javascript add tag before and after another

I've got this code:
<div id="pageNavigator" class="rbcContentBlock">
<ul>
Úvod
<span><span> > </span></span>
Fontánová čerpadla
<span><span> > </span></span>
<span id="navCurrentPage">Pontec PondoVario 1000</span>
</ul>
</div>
I would like to put "li" tags before and after tags "a". I tried to make something, here is my javascript code:
var div1 = document.getElementById("pageNavigator");
var elements = div1.getElementsByTagName("a");
var parentDiv = elements.parentNode;
var li = document.createElement("li");
parentDiv.insertBefore(li, elements);
What's wrong with this code? Is the problem that elements is "array"? Thanks for help.
This should wrap each anchors in a list item tag.
var div1 = document.getElementById("pageNavigator");
var ul = div1.children()[0];
var elements = div1.getElementsByTagName('a');
var(i = 0; i < elements.length; i++) {
var element = elements[i];
var li = document.createElement('li');
ul.replaceChild(li, element);
li.appendChild(element);
}

Categories