Show text only once

2

I have the following code:

// Re-usable var's
var cc = []; // Main array
var div = document.getElementById('array');
var t = "";
var w = "";
var c = "";

// End 

// Add element at first w/ push()

for(let i=0; i<=10; i++) {
  cc.push(i);
 w = document.getElementById("array");
 c = document.createElement("p");
 t = document.createTextNode("Push in array: " + i);
 c.appendChild(t);
 w.appendChild(c);
  
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="array"></div>
</body>
</html>

How can I display the word " Push in array " only 1 time , but still show the 10 numbers , unmodified? the HTML

That something like:

Push in array: 1 2 3 4 5 6 7 8 9 10
    
asked by Eduardo Sebastian 13.06.2017 в 04:40
source

1 answer

2

To be able to print the text once , you must use the loop, if you look you have this line:

t = document.createTextNode("Push in array: " + i);

Which means that you can access the value of the variable i , therefore you can play with a ternary operator, leaving your code like this:

t = document.createTextNode((i == 0 ? "Push in array: ": "") + i);

The ternary operator works in the following way:

((condicion) ? SI : NO)

If the condition is met , what will be done before the two points : , in case opposite will do what is after them.

So what we do is indicate the code, when the value of i is 0, print "Push in array" next to the value of i , otherwise, only print the value of i .

Note

To be able to print all the elements in a line, it would be enough to change this line:

c = document.createElement("p");

For this:

c = document.createElement("a");

So that instead of creating elements of type <p> , create elements of type <a> , which are only text, are not paragraphs like the <p>

tags

Voila, the example:

// Re-usable var's
var cc = []; // Main array
var div = document.getElementById('array');
var t = "";
var w = "";
var c = "";

// End 

// Add element at first w/ push()

for(let i=0; i<=10; i++) {

  cc.push(i);

  w = document.getElementById("array");
  c = document.createElement("a");
  t = document.createTextNode((i == 0 ? "Push in array: ": "") + i);

  c.appendChild(t);
  w.appendChild(c);
  
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="array"></div>
</body>
</html>
    
answered by 13.06.2017 / 04:55
source