TextNode addEventListener

Why can't I add an event listener to the node text 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

+4
source share
2 answers

Text nodes simply do not fire most events: historically, elements have been responsible for doing this in the HTML DOM. However, text nodes block some events (except IE <= 8): DOM mutation events . Especially useful for text nodes is DOMCharacterDataModified , which is used to detect text changes in node text and can be useful in browser-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); 
+6
source

Text nodes are simply β€œNode instances,” and according to the DOM specifications, they simply cannot listen to events. This is not something that would violate natural law, but it is not how the DOM works.

+4
source

Source: https://habr.com/ru/post/1336899/


All Articles