Passing and getting an array displayed as html text - javascript

I'm passing an array of strings to be displayed as html text inside a
my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"]
which is displayed as :
PRODUCT, SHAMPOO1, SHAMPOO2, SHAMPOO3, SHAMPOO1.
What I want to do is make these clickable. And when I click on one of these words I want that word to be displayed below it.
What's the cleanest way to do this?
Passing the array in the <a> tag isn't working for me.

you can add it to the DOM, then loop your array to the li under ul
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<div id="products"></div>
<body>
<script>
var my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"];
var str = "<ul>";
my_arr.forEach(function (product) {
str += "<li> <a href='/'>" + product + "</a> </li>";
});
str += "</ul>";
document.getElementById("products").innerHTML = str;
</script>
</body>
</html>

Related

Add dynamic tags in js

Hope you are doing well.
I have an input and when I enter a number and press on button it should create *x p tags. When I update the value of input and press on button it should display new *x p tags but it does not remove the previous value and adds new one. Here is my code.
Thank you!
create.addEventListener("click" , () => {
let inp = inp1.value
for(let i = 0; i < inp ; i++){
let newELement = document.createElement("p")
newELement.innerHTML = i+1
document.body.append(newELement)
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="inp1">
<br>
<button id="create">Create</button>
</body>
<script src="script.js"></script>
</html>
For this particular scenario , you can use a common class for all the creating elements
By doing this , we can get all the existing elements of that particular class and remove it in a single step.
create.addEventListener("click" , () => {
document.querySelectorAll('.nums').forEach(e => e.remove());
let inp = inp1.value
for(let i = 0; i < inp ; i++){
let newELement = document.createElement("p")
newELement.className += " " + "nums";
newELement.innerHTML = i+1
document.body.append(newELement)
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="inp1">
<br>
<button id="create">Create</button>
</body>
<script src="script.js"></script>
</html>
As I see it, when a user clicks Create, you want to:
Remove the previous tags, if any exist
Create and add the new tags
You've gotten step 2 down already, but you just need to remove the tags before you render the new ones, to get your desired output.
The easiest way to do this would be to, instead of placing the tags directly in the body, place them in a separate div, specifically for tags. Then you just empty that div when Create is clicked.
So, in your HTML, you add a div specifically for the tags:
<body>
<input type="text" name="" id="inp1">
<br>
<button id="create">Create</button>
<div id="tags"></div>
</body>
<script src="script.js"></script>
...and, in your JS, you just place the tags in that div, instead of the body, whilst emptying it every time Create is clicked:
let tags = document.getElementById("tags")
create.addEventListener("click" , () => {
let inp = inp1.value
tags.innerHTML = "" // empty tags div first
for(let i = 0; i < inp ; i++){
let newELement = document.createElement("p")
newELement.innerHTML = i+1
tags.append(newELement) // add to tags div, not body
}
})
Run and edit this code online

Javascript. Why won't my string replace update show in my browser

I am trying to change the word "lion" to "monkey" by using a function by using .replace in Javascript. I have set a time interval on it and it does work, but only in the console. Not in the browser when I am viewing the page. Why? Do I need to assign/update/upload it to the HTML somehow?
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
}
setInterval(toggleCaps, 3000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="about">
<blockquote>
<p>
lion
</p>
</blockquote>
</div>
</body>
</html>
You need to update the html element with the replaced string as following:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
document.querySelector(".about").innerText = sum; //add this
console.log(sum);
}
setInterval(toggleCaps, 3000);
yes you need to update the html:
function toggleCaps(){
let text = document.querySelector(".about").innerText;
console.log(text);
var sum = text.replace(/lion/g, "monkey");
console.log(sum);
document.querySelector(".about").innerText = sum;
}

InnerHTML- fetching from script

I am trying to display random numbers from 1 to 7. I do not want them to repeat and I want to display every number. I've written my JS code inside script tag. I want to get a random number whenever button is clicked, instead I'm getting error
Uncaught TypeError: Cannot set property 'innerHTML' of null
at grandom (fe.html:48)
at HTMLButtonElement.onclick (fe.html:25)
Below is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Goplan Project Selection</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.1/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<div class="text-center">
<img src="cissoiree.jpg" width="80px" height="80px">
<h1 style="text-size:300em">Go-Plan</h1></div></div>
<div style="padding-top:20px;" class="text-center">
<button class="btn-lg btn-primary" onclick="grandom()">Click!</button>
<p id="demo"><p>
</div>
<script type="text/javascript">
function grandom()
{
var q=[2,3,1,5,4,7,6];
var x=7;
var i;
x=q.length;
var random;
while(1)
{
random = Math.floor(Math.random()*x);
if(random<=q.length)
break;
}
document.write("<br>");
document.write("Question No : " + q[random] );
if(q.length!=1)
<!--document.write("<input type=button value=click here onclick=grandom();><br>");-->
document.getElementById("demo").innerHTML = q[random];
q.splice(random,1);
document.write("<br>");
}
</script>
</body>
</html>
After document.write(...); there is no other elements in the page expect the passed text.
It is why when you trying to find then document.getElementById("demo") it's cannot find, and return null. (then throw error, when you trying to access its innerHTML)
If you trying to append something to the page you should use document.body.innerHTML += "...".
About the algorithm itself - you can use:
[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});
It will shuffle the array randomly.
Your document.write(..) is breaking it.
You can try:
document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';

Get all innerhtml contents of span tags

I am trying to get the content of all span tags that are children of div#parent and I am not able to do it, I just get the first one. Could someone help me, please!
$( document ).ready(function() {
var allspans=$("#parent").find("span").html();
console.log( allspans );
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>jQuery</title>
</head>
<body>
<div id="parent">
<span>Element_1</span>
<span>Element_2</span>
<span>Element_3</span>
<span>Element_4</span>
<span>Element_5</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>
Thank you!
Best Regards!
You can iterate over the span's using .each, and then access their individual innerHTML's like this. Through the .each you can then combine the inner HTML content in an array or string.
Or, you could get the inner text of all span's by $("#parent").text().
$(document).ready(function() {
$("#parent").find("span").each(function() {
console.log($(this).html());
});
console.log($("#parent").text());
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>jQuery</title>
</head>
<body>
<div id="parent">
<span>Element_1</span>
<span>Element_2</span>
<span>Element_3</span>
<span>Element_4</span>
<span>Element_5</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>
JQuery is slow and unnecessary for that.
spans = document.getElementById("parent").getElementsByTagName("span");
returns an array of all spans in parent.
At this point the task is complete, as I could understand it: spans[span_number].innerHTML is what you want.
Then just parse that spans array in any way (foreach or whatever you like):
for(var i = 0, len = spans.length; i < len; i++ )
{
console.log(spans[i].innerHTML);
}
Avoid JQuery in any means (when possible) to make your code more independent, fast, less resource-intensive and robust. Save traffic.
Try with map() and get() function .You will get the all the span tag innerHTML with in array
$( document ).ready(function() {
var allspans=$("#parent").find("span").map(function(){
return $(this).html();
}).get()
console.log( allspans );
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>jQuery</title>
</head>
<body>
<div id="parent">
<span>Element_1</span>
<span>Element_2</span>
<span>Element_3</span>
<span>Element_4</span>
<span>Element_5</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>
You need to use some loop until $("#parent").find("span").length, by default jquery html function will returns the first matched element content:
var html = '';
var allspans = $("#parent").find("span");
for(var i=0;i<allspans.length;i++){
html += allspans[i].innerHTML;
}
$( document ).ready(function() {
var allspans=$("#parent").find("span");
var allSpanHtml = '';
allspans.each(function() {
allSpanHtml += $(this).html();
});
console.log( allSpanHtml );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div id="parent">
<span>Element_1</span>
<span>Element_2</span>
<span>Element_3</span>
<span>Element_4</span>
<span>Element_5</span>
</div>
You can use .each() to iterate through an array of element, and then use .html() to get text from individual element.
You would need to loop through each span matched by the selector and console log each html value or concatenate them into a variable or push them to an array variable; depending on whatever works best.
Do something like:
$( document ).ready(function() {
$("#parent").find("span").each(function(){
console.log( $(this).html() );
});
});
to log the html value of each span.
Try this
var arraySpan = [];
$('span').each(function() {
arraySpan.push(this.innerHTML);
});

How to create a button on the second page?

<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints()
{
var points=prompt("How many points have you earned?");
document.write("<p>Buy your items now and prepare for battle! Choose wisely.<p>" );
document.write("<p><img src = 'sword.jpg'/><p>");
document.write("<p><img src = 'Waterskin.jpg' /><p>");
document.write("<p><img src = 'charm.jpg' /><p>");
document.write("<p><img src = 'Phone.jpg' /><p>");
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
<div>
<input type="button" onclick="buyStuffWithPoints()" value="Buy Sword(2500)!" />
</div>
</body>
</html>
So currently what happens is when I run it, it prompts me to enter amount of points, then it shows two buttons, "Start!" and "Buy Sword(2500)!". Then after clicking start, the next page shows 4 pictures of the items to buy.
What I want to happen is, after I enter the amount of points, I only want it to show the "Start!" button. Then on the NEXT page, the same page where the pictures show up, I want to show the "Buy Sword" button.
I understand why it's doing this, I just have no idea how to change it. Can anyone help me with this?
You must close your p tags and you should avoid document.write
<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints() {
var points = prompt("How many points have you earned?");
var html = "<p>Buy your items now and prepare for battle! Choose wisely.</p>"
+ "<p><img src = 'sword.jpg'/></p>"
+ "<div><input type=\"button\" onclick=\"buyStuffWithPoints()\" value=\"Buy Sword(2500)!\" /></div>"
+ "<p><img src = 'Waterskin.jpg' /></p>"
+ "<p><img src = 'charm.jpg' /></p>"
+ "<p><img src = 'Phone.jpg' /></p>"
document.body.innerHTML = html;
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
</body>
</html>

Categories

Resources