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>
Related
I'm trying to loop through an array until it matches the value of the object that is clicked.
When the object is created the text input box shares it's value with the object and the array. I would like to be able to loop through the array until there is a match, then find the index, after that pass the index value to a variable to be used. From there remove the object that is clicked from the webpage and the array.
Additional details are that there is an input box with a button. The user enters a line of information into the input box and selects a button to appendChild it to the list. The object created is a div with the input value as the paragraph with a span element with an X which is supposed to remove the object when clicked.
Here is the HTML Code being used
<div id="outerDiv">
<div id="taskList">
</div>
</div>
Here is the code to create the object.
var magicArray = [];
function makeOutline() {
var textValue = document.getElementById("inputBox").value;
if (textValue == "" || textValue == null){
alert("Please enter a item you want to add to the to-do list");
} else {
var inputField = document.getElementById("taskList");
var inputText = document.createTextNode(textValue);
var mainHeading = document.createElement("p");
mainHeading.setAttribute("class", "outlineBorder");
var spanText = document.createTextNode("x");
var spanBox = document.createElement("span");
spanBox.setAttribute("class", "close");
spanBox.setAttribute("onclick", "removeMe()");
var outlineList = document.createElement("div");
outlineList.setAttribute("value", textValue);
spanBox.appendChild(spanText);
mainHeading.appendChild(inputText);
mainHeading.appendChild(spanBox);
outlineList.appendChild(mainHeading);
inputField.appendChild(outlineList);
magicArray[magicArray.length] = textValue;
document.getElementById("inputBox").value = "";
}
}
Here is the code to remove the item.
I am able to have it set to a static number and work every time; however,
struggling to find a dynamic solution since there can be multiple objects.
function removeMe() {
var removeList = document.getElementById("taskList");
removeList.removeChild(removeList.childNodes[1];
}
Here is a screenshot of the family tree structure
First, you can use this to get the element. docs:
When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered.
function removeMe()
{
// this refers to the item that invoked removeMe()
var removeList = document.getElementById("taskList");
removeList.removeChild(this.parentNode.parentNode);
}
Also, this is how you properly add event listeners
spanBox.addEventListener("click", removeMe);
Here is a working jsfiddle for you
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!
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);
I am trying to learn how to clone an element using classname and append it to the body.
here is what i have done but i am not getting any output. is there anything wrong ?
HTML:
<div class="check">hello</div>
CSS:
.check {
top: 100px;
}
JavaScript:
var elem = document.getElementsByClassName('.check');
var temp = elem[0].clonenode(true);
document.body.append(temp);
JSFiddle Link:
http://jsfiddle.net/hAw53/378/
if not JS, jquery solution is also welcomed.
You were almost there:
var elem = document.getElementsByClassName('check'); // remove the dot from the class name
var temp = elem[0].cloneNode(true); // capitalise "Node"
document.body.appendChild(temp); // change "append" to "appendChild"
<div class="check">hello</div>
You have 3 errors. Correct code:
var elem = document.getElementsByClassName('check'); // check, not .check
var temp = elem[0].cloneNode(true); // cloneNode, not clonenode
document.body.appendChild(temp); // appendChild, not append
Demo: http://jsfiddle.net/hAw53/379/
There are a few issues with your code.
getElementsByClassName() takes a class name (check), not a selector (.check)
cloneNode() is spelled with a capital N (not clonenode())
appendChild() is the name of the DOM method for appending a child (not append())
Correct version:
var elem = document.getElementsByClassName('check');
var temp = elem[0].cloneNode(true);
document.body.appendChild(temp);
You can do:
$('.check').clone().appendTo('body');
You're code had errors. First you used class selector and not the class name. Then you used an undefined property(properties are case sensitive) and you've to use appendChild instead of append which is a part of jQuery. You're too much confused with native javascript and jQuery.
in Jquery it's very simple, you just need to define inside what the new element apears.
var elem = $('.check');
elem.clone().prependTo( "body");
I'm looking to convert a function that selects by id to select the next instance of a given class.
Here is the code.
function swap3(oldDivId, newDivId) {
var oldDiv = document.getElementById(oldDivId);
var newDiv = document.getElementById(newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
Suppose you have this HTML:
<div id="test"></div>
<img>
<br>
<div></div>
<input>
<div class="abc">Found it</div>
<div class="cdf"></div>
Updated at 2021
The original answer is quite old now. Since the original question have the jQuery tag, the answer keeps valid and usable. But for those coming here with the hope to see an updated JavaScript code with no dependency on jQuery, take a look on how querySelector is a awesome nowadays:
const next = document.querySelector('#test ~ .abc')
next.textContent = 'Yeah, you found it!'
So the secret is to use the general sibling combinator that matches all iterations of the second element, but with querySelector that returns only the first match.
Original answer
So you select the first div by id:
var some = $("#test");
Then you want to find the next div with the class abc:
var next = some.nextAll("div.abc");
Suppose you want a variable as the className:
var x = "abc";
var next = some.nextAll("div." + x);
If I understand your question:
function nextItem(className) {
return $('#ID').closest('.' + className);
}
using closest: http://api.jquery.com/closest/
Select by ID in jQuery:
$('#class_name')
Select by class in jQuery:
$('.class_name')
Get the next item in jQuery:
$('.class_name').next('.class_name')
Using this, you can do something like
// Something to remember the current element
var currentElement = false;
function getNext(className)
{
// First time, there will be no current element
if (!currentElement)
{
currentElement = $('.' + className);
return currentElement;
}
// Other times...
currentElement = $(currentElement).next('.' + className);
return currentElement;