简体   繁体   中英

using appendChild to currently focused element

consider this code:

 console.log('New node') var node = document.createElement("div"); node.appendChild(document.createTextNode("+")); document.getElementById("elem").appendChild(node);
 <!DOCTYPE html> <html> <body> <div id="elem">+</div> </body> </html>

So this currently adds "+" as the text of a new div.

Say I want to add another child div with the text ">" to whatever div the user viewing index.html is currently focused on , considering the option he selected a div that was dynamically created, how may I accomplish this?

You need to set tab index on a div for it to be focusable, but then you can listen for the focus event and store the last focused element. You need to store your current item manually instead of relying on document.activeElement for getting the last focused element, since that would get changed to the button you are clicking.

 const appendbtn = document.querySelector('#appendit'); const addbtn = document.querySelector('#addbox'); let activeElement = null; let counter = 0; appendbtn.addEventListener('click', function() { if (activeElement) { const node = document.createElement('span'); node.textContent = '>'; activeElement.appendChild(node); } }); addbtn.addEventListener('click', function() { const text = document.createElement('span'); text.textContent = 'Box ' + (counter++); const box = document.createElement('div'); box.tabIndex = 0; box.classList.add('box'); box.addEventListener('focus', function() { if (activeElement) { activeElement.classList.remove('selected'); } activeElement = box; activeElement.classList.add('selected'); }); box.appendChild(text); const container = document.querySelector('.boxes'); container.appendChild(box); });
 .box { border: 1px solid #ddd; border-radius: 4px; margin: 1rem; padding: 1rem; } .box.selected { background-color: #f9f9f9; }
 <div class="boxes"> </div> <button id="addbox"> Add box </button> <button id="appendit"> Append chevron </button>

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