Binding event to text node

Here's my HTML. I need to bind a click event to "someText"

<div id="container">
    someText <a href="#">A link</a>

"someText" could be any string of text



Use jQuery to wrap the text node with a <span>, the place the click on that.

Try it out:

$('#container').contents()  // Get all child nodes (including text nodes)
               .first()     // Grab the first one
               .wrap('<span/>')    // Wrap it with a span
               .parent()           // Traverse up to the span
               .click(function() { alert('hi'); });??  // add the click to the span

The .contents() method returns all child nodes, including text nodes. So you grab the first child, wrap it, traverse to its parent (which is now the span), and add the click.


After a bit of messing I found a slightly better solution to Patrick's. It can select nodes after the link in this situation, making it more univerally usable. Probably better posting it here :)

.filter(function() {
    return this.nodeType == Node.TEXT_NODE;

Hacky way whithout any changing of html markup:

  1. Add contenteditable attribute to container.
  2. On click look at the selected node via document.getSelection() and check it.
  3. If selected text node is the very node, do what you want.
  4. Reset selection.

var el = document.getElementById("container")
el.setAttribute("contenteditable", "true") = "pointer" = "none"
el.addEventListener("click", function () {
  var selection = document.getSelection(),
      node = selection.baseNode

  if (node.nodeType == 3 && node.parentNode == el) {
    alert("someText are clicked")
el.addEventListener("keydown", function (event) {
  return false

PS: It's more food for thought rather than real recommendation.


Either wrap it in <a> or <div> tags and assign the click event to that element.

  <a href="#" id="sometext">someText</a>

  $("#sometext").click(function() {
       do stuff here...


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.