0

Pretty simple, but I'm doing something wrong. I want to do a nice clean chain here, rather than declaring a var and then concatenating it:

the_function( null, null, 
   $( this ) // START string I'm passing as a parameter
   .attr( 'data-href' )
   .html( '|foo:' + event.var ) 
); // END string I'm passing as a parameter

I realize that .html() is invalid here, what is correct?

8
  • What is your desired outcome, and why do you want method chaining to do string concatenation? Commented Oct 25, 2012 at 19:18
  • FYI, there's no such thing as "jQuery chaining". Chaining is simply the ability to immediately call a method on a value that was returned from a previous call. Commented Oct 25, 2012 at 19:25
  • @user1689607 that's just nit-picking. You are operating on the jQuery Object so you could as well call it jQuery chaining... Commented Oct 25, 2012 at 21:29
  • @Christoph: I disagree. I believe plenty of people think chaining is a feature that is caused by some jQuery magic. Anyway, it makes as much sense to call it jQuery chaining as it does to say I'm going to McDonald's to do some McDonald's eating. Commented Oct 25, 2012 at 21:40
  • @user1689607 I agree, many people don't even know that jquery is just plain javascript. Please if you nitpick next time say: chaining is a technique of subsequently calling a function-property of the previously returned object. Values have no properties and javascript has no methods in the classical sense. Commented Oct 25, 2012 at 22:05

3 Answers 3

3

Huh? do you mean to do something like this

the_function( null, null, 
   $( this ) // START string I'm passing as a parameter
   .attr( 'data-href' ) +  '|foo:' + event.var); 

What you had

$( this ).attr( 'data-href' ) // returns a string.. it doesn't have a html method
Sign up to request clarification or add additional context in comments.

1 Comment

@Brian Sometimes it's most obvious that we overlook :P
0

I'm not really sure what you want to accomplish but here are some notes:

  • you can use .data() method for data- attribute
  • you can't use .html() on .attr(), you need to use html() on $(selector)

So, basically, you could use this:

$(this).html('|foo:' + event.var).data('href')

Comments

0

I'm not sure what the outcome is that you want, but if you really want method chaining, you could chain the native .concat() method to the string.

the_function( null, null, 
   $( this ).attr( 'data-href' )
            .concat('|foo:', event.var) 
);

Or separate .concat() calls if you really dig the chaining.

the_function( null, null, 
   $( this ).attr( 'data-href' )
            .concat('|foo:')
            .concat(event.var) 
);

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.