Include a name attribute while adding to an <ol> - javascript

I'm working on a website that has a dynamic list in it and I want to be able to access individual elements in the list.
Is there a way to add a name to each element when using appendChild()?
This is my function:
function addOrder(theName, thePrice) {
var li = document.createElement("li");
var t = document.createTextNode(theName);
li.appendChild(t);
document.getElementById("cart").appendChild(li);
}

Do you mean adding a name or data to each element so you can access it at some later time in JS? If so you would want a data-attribute, which you set by using the dataset property.
function addOrder(theName, thePrice) {
var li = document.createElement("li");
// Add a data attribute with name of data-name and value of theName:
li.dataset.name = theName;
var t = document.createTextNode(theName);
li.appendChild(t);
document.getElementById("cart").appendChild(li);
}
In future code you can now look for a list item with a specific name by using something like this: document.querySelectorAll("[data-name='some name']"); or you could get all list items and filter them:
const listItems = document.querySelectorAll("#cart li");
const nameIWantToFind = 'some name';
const foundName = Array.from(listItems).filter(item => item.dataset.name === nameIWantToFind);
Also, as others have said, you don't need to use createTextNode. You can use textContent instead. Others have suggested innerHTML which will work, but isn't needed if you only plan to insert text, and textContent should have slightly better performance. Here is how you would rewrite the function:
function addOrder(theName, thePrice) {
// It's neater to put your DOM elements in variables at the top of the function
var cart = document.getElementById("cart");
var li = document.createElement("li");
// Add the text inside the `li` element:
li.textContent = theName;
// Add a data attribute with name of data-name and value of theName:
li.dataset.name = theName;
// Append the `li` element to the `#cart` using the variable we defined at the top of the function:
cart.appendChild(li);
}

Definitely!
Here you go:
== UPDATED with ES6 ==
function addOrder(theName, thePrice) {
// Select your `ul` element
const list = document.querySelector("#cart");
// Create `li` element
const li = document.createElement("li");
// Add your dynamic HTML to the `li`
li.innerHTML = theName;
// Append your `li` to your `ul`
list.appendChild(li);
}
Have any concerns? Feel free to comment!

Related

JavaScript | appendChild to all classes

I have problem with append Child to whole classes in my document which the name of class is "onbackorder". Here is my code:
<script>
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
var isRequestQuote = document.getElementsByClassName('onbackorder');
if (isRequestQuote.length > 0) {
document.querySelector(".onbackorder").appendChild(first);
}
</script>
For this moment function put selector randomly. How can I get same selector in whole document where class is "onbackorder".
Thank you
There are 2 points:
document.querySelector(".onbackorder") is just return first item. So you need to use document.querySelectorAll('.onbackorder').
The Document method querySelector() returns the first Element within
the document that matches the specified selector, or group of
selectors. If no matches are found, null is returned.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var first = document.createElement("p"); you have to create multiple reference variable to append to each onbackorder item. Because you cannot create only one and append to multiple items.
So I modified your code and make it works. You can check it at below:
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
const allBackOrders = document.querySelectorAll('.onbackorder');
allBackOrders.forEach((item) => {
var newItem = first.cloneNode(true);
item.appendChild(newItem);
});
<div class="onbackorder"></div>
<div class="onbackorder"></div>
<div class="onbackorder"></div>

Finding which row has been selected in a getmdl-select

I have the following code to populate a drop down using getmdl-select
var ul = document.getElementById('allocateToUL');
result.forEach(function (u) {
var li = document.createElement('li');
var dataVal = document.createAttribute('data-value');
var dataSelector = document.createAttribute('data-selector');
dataVal.value = u.Id;
dataSelector.value = u.Id;
li.innerText = u.FriendlyName;
li.className = 'mdl-menu__item';
li.setAttributeNode(dataVal);
li.setAttributeNode(dataSelector);
ul.appendChild(li);
// note call getmdlSelect.init once item is added
getmdlSelect.init('.getmdl-select');
componentHandler.upgradeAllRegistered();
});
What I do not seem to be able to do is find out which option is selected here;
I have tried
document.getElementsByClassName('mdl-menu').find('li.active')
But that just tells me 'find' is not a function although it getElements.... does return list of elements.
Any suggestions?
It looks like you want to use the jQuery find method, but you are not using a jQuery selector. Try replacing:
document.getElementsByClassName('mdl-menu').find('li.active')
With:
$('.mdl-menu').find('li.active')

functions don't no longer work after rewriting code into javascript

I have a list with people's data inside it has a li element with 3 p tags inside, one for name, one for address and one for email.
I filled this list manually but due to some changes to my code I had to rewrite this so the html would be made with javascript.
My code looked like this
<p class="adres">#logopedist.Adres</p>
<p class="email">#logopedist.Email</p>
<p class="mobiel">#logopedist.Mobiel</p>
I rewrote this to build the html using javascript. This looks something like this.
var li = document.createElement('li');
li.className = "lijst";
li.id = "lijst";
li.onclick = "ficheVullen(this)";
p.className = "naam";
p.innerHTML = objLogos.Naam[i];
li.appendChild(p);
p.className = "adres";
p.innerHTML = objLogos.Adres[i];
li.appendChild(p);
var p = document.createElement('p');
p.className = "mobiel";
p.innerHTML = objLogos.Mobiel[i];
li.appendChild(p);
My list generates properly. But in my old code I had this at the start of the list.
<li class="lijst" onclick="ficheVullen(this)">
Whenever you would click an li element it would fill a div with the info from the p tags inside that li, so it would fill the div with name, address, mobile,etc
I cannot seem to get this function to work anymore. It only works on the very first LI element and only works for the name. Even though my code is the same and I append classes to the tags like it had in my old code.
The function looks like this:
function ficheVullen() {
FicheNaam = document.getElementById("FicheNaam");
FicheAdres = document.getElementById("FicheAdres");
FicheGSM = document.getElementById("FicheGSM");
FicheNaam.innerHTML = this.querySelector('.naam').textContent;
FicheGSM.innerHTML = this.querySelector('.mobiel').textContent;
FicheAdres.innerHTML = this.querySelector('.adres').textContent;
I get this error now. Cannot read property 'textContent' of null
I call this function here:
window.onload = function() {
changePage(1);
document.getElementById("lijst").addEventListener("click", ficheVullen);
};
The changepage function is part of my pagination where I use javascript to build the list.
When I move the eventlistener out of this I get this error: Cannot read property 'addEventListener' of null.
I hope this gives enough context
You have to use setAttribute to set id.
elm.setAttribute("id", "uniqueId");
Your case : li.setAttribute("id", "lijst")
li.id = "lijst"; will add "id" to object not as attribute
const parent = document.getElementById("container")
let elm = document.createElement("p")
elm.setAttribute("id", "pElm")
elm.innerText = "p tag"
parent.append(elm)
document.getElementById("pElm").style.background = "red"
<div id="container"></div>

What are the equivalent of after and before jQuery's function in native javascript?

I always used jQuery before, but I want to switch the following to native javascript for better performance of the website.
var first = $('ul li:first');
var first = $('ul li:last');
$(last).before(first);
$(first).after(last);
From: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/
Before (prepend):
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
After (append):
// Grab an element
var el = document.getElementById('thingy'),
// Make a new div
elChild = document.createElement('div');
// Give the new div some content
elChild.innerHTML = 'Content';
// Jug it into the parent element
el.appendChild(elChild);
To get the first and last li:
var lis = document.getElementById("id-of-ul").getElementsByTagName("li"),
first = lis[0],
last = lis[lis.length -1];
if your ul doesn't have an id, you can always use getElementsByTagName("ul") and figure out its index but I would advise adding an id
I guess you are looking for:
Element.insertAdjacentHTML(position, text);
Where position is:
'beforebegin'.
Before the element itself.
'afterbegin'.
Just inside the element, before its first child.
'beforeend'.
Just inside the element, after its last child.
'afterend'.
After the element itself.
And text is a HTML string.
Doc # MDN
You can use insertBefore():
var node = document.getElementById('id');
node.parentNode.insertBefore('something', node);
Documentation: insertBefore()
There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling():
node.parentNode.insertBefore('something', node.nextSibling);

How to remove an specific <li> with pure javascript

I'm trying to figure out, how am i able to delete a specific <li> with pure javascript ?
My purpose is: each <li> does have a "remove" button and if we click on that button, it will remove that <li>.
function remove(r){
**REMOVE**
}
function add(){
var ul = document.getElementById("ul");
var li = document.createElement("li");
if(document.getElementById("nameS").value && document.getElementById("mailS").value){
var nameS = document.createElement("i");
nameS.innerHTML = document.getElementById("nameS").value;
nameS.innerHTML += ": ";
var mailS = document.createElement("font");
mailS.setAttribute("color","#000080");
mailS.innerHTML = document.getElementById("mailS").value;
mailS.innerHTML += " - ";
if(document.getElementById("webpageS").value){
mailS.innerHTML += ""+document.getElementById("webpageS").value+"";
}
var element = document.createElement("input");
element.setAttribute("type","button");
element.setAttribute("value","Remover");
//element.setAttribute("onclick",remove());
element.addEventListener('click',function(){
li.remove();
},false);
li.appendChild(nameS);
li.appendChild(mailS);
li.appendChild(element);
ul.appendChild(li);
}
}
If you add your remove function using addEventListener as suggested by #Eevee, the first argument passed to remove will be an Event object. (For a click event, it will be a MouseEvent object.)
Every Event object has a property, target, which tells you where the element came from. So, you can simply go up the tree of elements to get the li, and remove that:
function removeParent(evt) {
evt.target.parentNode.remove();
}
element.addEventListener('click', removeParent, false);
Some other comments on your code:
Please don't ever use font elements; likewise i elements. You should use span if you want to apply styles; if you want to emphasise text, use em.
What i would do would be to add a unique id to each of the li's that you can later reference to remove it:
var curId = 0;
function add(){
....
var li = document.createElement("li");
li.setAttribute(id,curId)
...
curId++;
}
Then in your button pass that id
element.setAttribute("onclick",remove(curId));
Then for your remove function it is simply:
function remove(ele){
ducument.getElementById(ele).remove();
}

Categories