Reputation: 59
I want to add a created element li with a classname stored in an array, and I want to add this new element li with special classname to a static element with an id. I have an error appenChild is not a function. We are inside an JS object btw. The console display the right thing, it shows me the li with the good classname, but i cant add it to the id stacks-icons.
I would like the final result to be : adding in my ul a new li with a classname i have chosen in the array icons.
here the HTML and JS :
<ul id="stacks-icons">
<li></li>
</ul>
And the JS ( variables in constructor )
this.icons = ["fab fa-html5", "fab fa-css3"];
this.iconsRow = $('#stacks-icons');
And the method
let i = document.createElement('li');
i.className = this.icons[1];
this.iconsRow.appenChild(i);
console.log(i);
Upvotes: 2
Views: 72
Reputation: 1425
Use appendChild
instead of appenChild
. Also, use document.querySelector
to select the dom element.
If you are using jQuery, then use append()
instead of appendChild()
because you are getting the element by a jQuery method so you should use jQuery method for appending as well. Check this question for more info.
An example snippet is below -
class Iconlist{
constructor(){
this.icons = ["fab fa-html5", "fab fa-css3"];
this.iconsRow = $('#stacks-icons');
}
create(){
let i = document.createElement('li');
i.textContent = "Some text";
i.className = this.icons[1];
this.iconsRow.append(i);
console.log(i);
}
}
let mi = new Iconlist();
mi.create();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="stacks-icons">
<li>ABC</li>
</ul>
Upvotes: 2
Reputation: 2720
There is no method called appendChild
if you select that element using jQuery
. Jquery has append
method by which you can append an element in your ul
. I've added both ways(jquery and javascript) here in which you can achieve your goal. Here is the working example:
var icons = ["fab fa-html5", "fab fa-css3"];
// 1st way using javascript
var ul = document.getElementById("stacks-icons");
let i = document.createElement('li');
i.className = icons[0];
i.appendChild(document.createTextNode("1st using javascript"));
ul.appendChild(i);
// 2nd way using jquery
var iconsRow = $('#stacks-icons');
let i1 = document.createElement('li');
i1.className = icons[1];
i1.appendChild(document.createTextNode("2nd using jquery"));
iconsRow.append(i1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<ul id="stacks-icons">
<li>Default</li>
</ul>
Upvotes: 2
Reputation: 99
Use querySelector to find DOM element and change appenChild to appendChild like this
let icons = ["fab fa-html5", "fab fa-css3"];
let ir = document.querySelector('#stacks-icons');
let i = document.createElement('li');
i.className = icons[1];
ir.appendChild(i);
Upvotes: 4