Get id of elem changed when event is attached to document

49 Views Asked by At

Points to be noted:

  • The whole document is content editable
  • The body has an input event attached to it
  • I need to get the id of the specific element which was changed
  • Only vanilla Javascript is allowed

e.g : If I change Tom to Paul, I should get m1 as id.

Problem: e.target returning the body element instead specifc element(div#m1)

document.body.contentEditable = true;
document.body.addEventListener('input', e => {
  console.log(e.target)
})
<div id="m1">Hello Tom</div>
<div id="m2">Hello Sam</div>

2

There are 2 best solutions below

2
boisvert On

A problem is - if the whole body is editable, how do you know what elements will remain, or be removed altogether, or even added, when your user starts editing?

Is it acceptable to you to have each of the different elements marked as editable independently? As per the snippet below.

document.getElementById('m1').contentEditable = true;
document.getElementById('m2').contentEditable = true;

document.body.addEventListener('input', e => {
  console.log(e.target)
})
<div id="m1">Hello Tom</div>
<div id="m2">Hello Sam</div>

It's also possible to set each element editable using a loop of course, to not repeat code and to adapt to different document structures automatically.

5
Rohit.007 On

I have added e.target.id in your console. Hope this works for you

document.body.contentEditable = true;
document.body.addEventListener('input', e => {
  console.log(e.target.id);
})
<div id="m1">Hello Tom</div>
<div id="m2">Hello Sam</div>