5

Why can I not add a event listener to the text node itself instead of the p element?

<p>childNode</p>
...
p.childNodes[0].addEventListener('click',function(){alert('ok')},false)

When I click on childNode nothing happens in chrome

Gert Cuykens
  • 6,845
  • 13
  • 50
  • 84

2 Answers2

9

April 2021 Update

DOM mutation events such as DOMCharacterDataModified are now deprecated, and MutationObservers should be used instead.

Original answer

Text nodes simply don't fire most events: historically, elements have had the responsibility for doing that in HTML DOMs. However, text nodes do fire some events (except in IE <= 8): DOM mutation events. A particularly useful one for text nodes is DOMCharacterDataModified, which is used to detect change to a text node's text and can be useful in browser-based editors.

Example: http://www.jsfiddle.net/timdown/c6dHX/

HTML:

<div contenteditable="true" id="div">A text node, edit me</div>

JavaScript:

var textNode = document.getElementById("div").firstChild;

textNode.addEventListener("DOMCharacterDataModified", function(evt) {
    alert("Text changed from '" + evt.prevValue + "' to '" + evt.newValue + "'");
}, false);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I am currently using MutationObservers, but normal events seem to generate cleaner code. Is it deprecated or can I still use DOMCharacterDataModified? – Eduardo Poço Apr 27 '21 at 19:43
  • 1
    @EduardoPoço: DOM mutation events such as `DOMCharacterDataModified` are deprecated, so you should carry on with `MutationObserver`s. I'll update my answer. – Tim Down Apr 28 '21 at 00:10
5

Text nodes are just plain "Node" instances, and according to the DOM specs they just can't have event listeners. It's not something that would violate natural law, but it's just not the way the DOM works.

Correction: apparently (thank you Jens) they can have listeners, but most events (including common ones like "click") are not fired on text nodes.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    That's not true. The type hierarchy is Text <: CharacterData <: Node <: EventTarget. Thus, Text has the method addEventListener. However, it does not fire the click (or most other) events. – Jens Sep 28 '22 at 15:15