2

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>
TechXpert
  • 155
  • 2
  • 3
  • 10

2 Answers2

1

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.

boisvert
  • 3,679
  • 2
  • 27
  • 53
0

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>
Rohit.007
  • 3,414
  • 2
  • 21
  • 33
  • It doesn't work because `e.target` is returning the body and I need the exact `div element` – TechXpert Jun 15 '18 at 16:19
  • I have checked, It will return the element where the change has been made. Are you updating these elements? because if you try the same code in the browser console. say do in the same stack overflow tab and try typing in the above search then you will get the search element ID currently it is blank in this case – Rohit.007 Jun 15 '18 at 16:22
  • Yes, blank in case of stackoverflow. because the search box is not having id – Rohit.007 Jun 15 '18 at 16:34
  • Why is the id blank if I am not updating the elements even in my text editor? – TechXpert Jun 15 '18 at 16:34
  • What do you mean by updating element? changing the values of element OR element itself ? – Rohit.007 Jun 15 '18 at 16:35