user677526
user677526

Reputation:

jQuery: setting an element attribute to .text()

I have a span tag that looks like the following:

<span class="myClass">Lorem ipsum</span>

I would like to add an attribute to it that references the innerText value (for a javascript function call), and I would like it to look like this:

<span class="myClass" data-bind="click: function(data, event) { myFunction('Lorem ipsum') }">Lorem ipsum</span>

I want to be able to dynamically parse a paragraph of text that contains spans of span myClass, and add the attribute programmatically. As such, if my innerText was "Sed", the argument to myFunction would be "Sed".

I tried the following to produce this:

jquery(container).find('.myClass').attr('data-bind', 'click: function(data, event) { myFunction(' + $(this).text() + ')}');

It didn't work. (The function argument was empty. Trying .html() outputs "null".)

Does anyone know how to accomplish something like this in jQuery? I believe that my issue is the $(this) keyword, as it's not pointing to the object in question. I'm not sure if there's another keyword that I can use...

Thank you!

Edit: Whoops, I attempted to obfuscate my code a little, and forgot to do it for the last line. Sorry for any confusion.

Upvotes: 0

Views: 656

Answers (3)

zhujy_8833
zhujy_8833

Reputation: 571

Yes, the keyword 'this' at this time refers to container. I think you can do:

var spans = jQuery(container).find('span');  //all spans
jQuery.each(spans,function(i,ele){
     var text = jQuery(ele).text();
     jQuery(ele).attr('data-bind','click: function(data, event) { myFunction("'+text+'")}');
});

Upvotes: 0

Rodik
Rodik

Reputation: 4092

Your code doesn't work because $(this) isn't your element.

try:

jquery(container).find('.nonGlossaryKeyword').each(function(){
   $(this).attr('data-bind', 'click: function(data, event) { showNonGlossaryModal(' + $(this).text() + ')}');
});

in this case, $(this) iterates over all the .nonGlassorayKeyword elements, like a for loop.

Upvotes: 2

Seth Flowers
Seth Flowers

Reputation: 9190

Do you mean:

jQuery(".myClass") // or $(".myClass")

instead of

jquery(container).find('.nonGlossaryKeyword')

Upvotes: 0

Related Questions