简体   繁体   中英

How to make elements added in JavaScript react the same as added in HTML?

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.

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;
}

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM