2

I have a string in which I like to replace some part with DOM element:

var mainStr = 'akedf abc dde';

var span = document.createElement('span');
span.id = 'word';
span.innerHTML = '123';
$(span).click(this.touchHandler);

var n = mainStr.replace('abc',span.innerHTML);

var htmlObject = document.createElement('div');
htmlObject.innerHTML = n;


touchHandler:function(e){
    console.log('log something')
},

this code does not work, the 'abc' string is replaced with '123' but the touchHandler does not work.

The code is in Backbone.js

Is there some way that I can do this?

3
  • 1
    Might help if you include the code for touchHandler if it's the bit that's not working. Commented Oct 4, 2013 at 9:04
  • 1
    you attach the click event to span, yet you only use span.innerHTML, this can't clone the event, so just attach the event to $('span',htmlObject) instead, and use outerHTML, not innerHTML Commented Oct 4, 2013 at 9:05
  • You seem to be using jQuery, so why bother with document.createElement() when jQuery lets you do the same thing with less typing? Commented Oct 4, 2013 at 9:09

2 Answers 2

2

Not like this. The way you insert the span into the document (var n = ...) treats the span as dumb HTML and leaves it to the browser to actually create the element and insert it into the DOM; your own span element is not inserted, therefore the click handler doesn't work.

You can attach the handler to the actual element this way:

var mainStr = 'akedf abc dde';

var span = document.createElement('span');
span.id = 'word';
span.innerHTML = '123';

var n = mainStr.replace('abc',span.innerHTML);

var htmlObject = document.createElement('div');
htmlObject.innerHTML = n; // the browser creates new span element
$(htmlObject).find("span").click(this.touchHandler); // click handler attached
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worked with one change var n = mainStr.replace('abc',span.outerHTML); as user2786485 suggested.
2
  1. you are attaching the event to a different element, that doesn't exist in htmlObject. you need to attach the event to the span element that is within htmlObject, because innerHTML doesn't copy event listeners

  2. when you use innerHTML you dont actually get "<span>123</span>", instead you get "123". you can either use span.outerHTML or just a string var spanString = "<span>123</span>"; and var n = mainStr.replace('abc',spanString);

example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.