Hi I am using code below, but getting 'undefined' as a result. How to fix this?
I am not sure how to call for a class within a class.
function myFunction() {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker").innerHTML;
}
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
Note: As getElementS states, getElementsByClassName returns an array like HTMLCollection.
So inorder to access the first element (your class inline-keyword-marker), you need to add [0] to your method like this:
document.getElementsByClassName('inline-keyword-marker')[0]
function myFunction() {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker")[0].innerHTML;
}
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
You might also to read this. It explains your issue more detailed than I did.
To handle all your classes, you can use this method:
function myFunction() {
var classes = document.getElementsByClassName('inline-keyword-marker'); // Get all elements
var myDiv = document.getElementById('mydiv'); // Get the div for the result
myDiv.innerHTML = ""; // At first, we clear the result div; not neccessary, just for the optic
// Because we got a HTMLCollection back, we need to loop through it
for (var i = 0; i < classes.length; i++) {
myDiv.innerHTML += classes[i].innerHTML + "<br>"; // With [i] we access every element -> at first the first one, then the second on and so on
// I also added a <br> tag, so the results get append beneath each other, not next to each other
}
}
<span class="inline-keyword-marker valid">Product1</span>
<span class="inline-keyword-marker valid">Product2</span>
<span class="inline-keyword-marker valid">Product3</span>
<span class="inline-keyword-marker valid">Product4</span>
<span class="inline-keyword-marker valid">Product5</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
Problem :
document.getElementsByClassName returns an array and not a single value so in order to select one you can do this [i] where is the index of the elements so :
document.getElementsByClassName("inline-keyword-marker")
becomes :
document.getElementsByClassName("inline-keyword-marker")[0]
and selects the first element with class inline-keyword-marker
So total JavaScript becomes :
myFunction = () => {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker")[0].innerHTML;
}
Shorter :
myFunction = () => (d=document).getElementById("mydiv").innerHTML = d.getElementsByClassName("inline-keyword-marker")[0].innerHTML
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
Related
I try to make a cart page with 'empty cart' button and 'add to cart' button. I want to make the list so it adds under each other. In my code each time I press "add to shopping cart" it comes right beside each other with no spaces(instead of coming on the next line). What should I do?
How do I also make an 'empty cart' button once I have all the products added, is there a method to remove all the nodes in the cart using a function?
window.onload = start;
function start()
{
console.log('start');
}
function addTo()
{
document.getElementById("output").innerHTML += document.getElementById("txtProduct").value;
}
function empty()
{
}
<label>Product</label> <input type="text" id="txtProduct">
<button onclick="addTo()">Add to shopping cart</button>
<button onclick="empty()">Empty cart</button>
<p id="output"></p>
Check this out:
window.onload = start;
function start()
{
console.log('start');
}
function addTo()
{
var product = document.createElement("p");
product.innerText = document.getElementById("txtProduct").value;;
document.getElementById("wrapper").appendChild(product);
}
function empty()
{
document.getElementById("wrapper").innerHTML = "";
}
<label>Product</label> <input type="text" id="txtProduct">
<button onclick="addTo()">Add to shopping cart</button>
<button onclick="empty()">Empty cart</button>
<div id="wrapper">
<p id="output"></p>
</div>
I added a wrapper div so you could clean it on "empty" action.
Also I used the JS createElement function to create a <p> element for each product, it's more clean and right than adding just text to element's innerHTML. That makes them line-seperated, too...
Just change your addTo function like this:
function addTo() {
var elem = document.createElement("p");
elem.innerHTML = document.getElementById("txtProduct").value;
document.getElementById("output").appendChild(elem);
document.getElementById("txtProduct").value = "";
}
What this does is that every time you call the function, you create a p element with the value of txtProduct, it then appends the elem to the DOM and clear the value of txtProduct so you do not have to clear it manually each time you enter a value.
Then, change your empty function:
function empty() {
document.getElementById("output").childNodes.forEach((node) => {
node.innerHTML = "";
})
}
This is the jsbin test
Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}
I'm looking at this fiddle: http://jsfiddle.net/npH8X/
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
addBox = function(){
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
anybody have javascript example like it, but showing exactly how I might give each of those boxes its own id either at its creation or right afterwards while I'm at it?
I want to create a writer's tool where they can type info into each box and then port all the inputs into one larger container afterwards, so the boxes need ids to do that...
thanks
All you need to do is set the .id property of the textbox after it is created, but before it is inserted to the DOM. This can correspond to a variable, and automatically increment based off of it:
var count = 3; // Corresponding to the existing textbox count
addBox = function() {
var textBox = document.createElement("textarea");
count++;
textBox.id = count;
document.getElementById("parent").appendChild(textBox);
console.log("New element's ID: " + textBox.id);
}
<div id='parent'>
<textarea id="1">txt1</textarea>
<textarea id="2">txt2</textarea>
<textarea id="3">txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
However, note that you don't need to give your <textarea> elements IDs in order to be able to target them. You use document.querySelectorAll() to return a collection of all textboxes, including those that have been dynamically created:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
checkBoxes = function() {
console.log(document.querySelectorAll("#parent textarea"));
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="checkBoxes()">check boxes</button>
Hope this helps! :)
Comment Answer:
.querySelectorAll() simply returns a node list of all of the <textarea> elements. As such, you can access the fourth element with 3 as an index (as it starts from 0). document.querySelectorAll("#parent textarea")[3] corresponds to the fourth <textarea>, and you can retrieve its contents with the .value property:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
var box4content;
getBox4 = function() {
if(document.querySelectorAll("#parent textarea")[3]) {
box4content = document.querySelectorAll("#parent textarea")[3].value;
}
console.log("The variable `box4content` has the value: " + box4content);
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="getBox4()">get box 4</button>
I dynamically create a form. There is an add line button that adds a new line that includes a delete line button.
I originally wrote this in angular, and I was able to pass "$index" into the function to remove the specific line.
I am now rewriting my code in pure js, and my question is: How can I go about implementing this same functionality?
The example for deleting elements by index as per your requirement can be found in this jsfiddle : https://jsfiddle.net/ChaitanyaMunipalle/9z73rfjx/2/. I assume you will take care of adding lines & delete buttons dynamically. It contains only deletion.
As you have not given any code, I assumed the html would look like the below one:
<div id="lines">
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
</div>
You have to add event listeners to delete buttons. And you have to use closure to save the index of the button clicked.
var deleteItem = function(index) {
var divElements = document.getElementsByClassName("line-item");
for (var i = 0; i < divElements.length; i++) {
if (i == index) {
divElements[i].parentNode.removeChild(divElements[i]);
break;
}
}
};
var deleteButtons = document.getElementsByClassName("delete-line");
for (var i = 0; i < deleteButtons.length; i++) {
(function(index){
deleteButtons[i].addEventListener('click', function() {
deleteItem(index);
}, false);
})(i);
}
I don't quite understand your setup, but removing a div is just
parentNode.removeChild(yourDiv)
If you only have the parentNode but know the index of the div you want to delete, then
parentNode.removeChild(parentNode.children[i])
`<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>`
This a example in jsfiddle:
https://jsfiddle.net/AlfonsoRamirez9/ttj1sLo5/
I hope help you :)
I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem