Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textNode addEventListener

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

like image 390
Gert Cuykens Avatar asked Jan 25 '11 02:01

Gert Cuykens


2 Answers

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);
like image 155
Tim Down Avatar answered Sep 28 '22 02:09

Tim Down


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.

like image 32
Pointy Avatar answered Sep 28 '22 00:09

Pointy