1

I am trying to add new elements in JavaScript, and when I hover my mouse over them I want to see how many letters are in the innerHTML. The function works on elements added in html, but the new ones not.

var input = document.getElementById("input")
var button = document.getElementById("button");
button.onclick = function () { 
 var p = document.createElement("p");
 p.innerHTML = input.value ;  
 document.body.appendChild(p);
 p.id="p";

}

var ar = document.getElementsByTagName("p"); 

for (var i = 0; i < ar.length; ++i) {

  ar[i].title=ar[i].innerHTML.length;
 
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input id="input"></input>
  <button type="button" id="button"> click</button>
  <p>p1</p>
  <p>p2</p>
</body>
</html>

What I want to achive: number of letters of element I hover on,

What I get: number of letters of elements I hover on, but only these that were added in html.

anzzz
  • 35
  • 3
  • https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli The answer here will help you understand how to do it – shabtai levi Apr 02 '21 at 10:30

2 Answers2

0

That happens because you are adding title only on page load. And titles are not added when new elements are created. You should do something like that on button click:

button.onclick = function () { 
   var p = document.createElement("p");
   p.innerHTML = input.value ;  
   document.body.appendChild(p);
   p.id="p";
   p.title = input.value.length;
}
john grad
  • 141
  • 1
  • 6
0

You could change your click handler like this:

button.onclick = function () { 
    var p = document.createElement("p");
    p.innerHTML = input.value ;  
    document.body.appendChild(p);
    p.id="p";
    p.title = input.value.length
}

it would be better to make a new function though, which will perform this code so that you have less code duplication, i.e. I'd rewrite it like this:

function applyFormatting(pElement) {
    pElement.title = pElement.innerHTML.length
}

button.onclick = function () { 
    var p = document.createElement("p");
    p.innerHTML = input.value ;  
    document.body.appendChild(p);
    p.id="p";
    applyFormatting(p);
}

var ar = document.getElementsByTagName("p"); 

for (var i = 0; i < ar.length; ++i) {
    applyFormatting(ar[i]);
}

that way the "formatting" you want to apply to your already existing p elements is centralized in a function and you know that the elements will undergo the exact same transformation.

Shikamu
  • 382
  • 1
  • 16
  • That works great. Maybe you know how do it the same, but onclick? I tried adding functions and your formatting method but still nothing. – anzzz Apr 02 '21 at 11:05
  • what do you want to do exactly ? display a tooltip when you click the P elements ? – Shikamu Apr 02 '21 at 14:11