views:

36

answers:

3

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

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

"someText" could be any string of text

A: 

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...
  });
Joey C.
I can't change the HTML.
Ben Shelock
+4  A: 

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

Try it out: http://jsfiddle.net/3F4p4/

$('#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.

patrick dw
A: 

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 :)

$('#container')
.contents()
.filter(function() {
    return this.nodeType == Node.TEXT_NODE;
})
.wrap('<span/>')
.parent()
.click(function(){
   alert($(this).text());
});
Ben Shelock