1

My div is called football, and this works:

$target.appendTo($('#football'));

But I dont want to hard code it, it needs to be more dynamic, how can I replace 'football' with the class name of the attribute:

$target.attr('class') //football

Thanks for any help!

panthro
  • 22,779
  • 66
  • 183
  • 324
  • 2
    possible duplicate of [How to use javascript variables in jquery selectors](http://stackoverflow.com/questions/5891840/how-to-use-javascript-variables-in-jquery-selectors) – Felix Kling Apr 22 '12 at 23:57
  • You are looking for [string concatenation](https://developer.mozilla.org/en/JavaScript/Reference/Operators/String_Operators). – Felix Kling Apr 22 '12 at 23:59
  • do you want to select by class or add a class to something you've previously selected? – tobyodavies Apr 22 '12 at 23:59
  • Wooot now? In the first one you are appending the target element to the element with ID football, in the second one you are getting the className of the target element, and that's also football. What exactly is it you are trying to do, I don't get it ? – adeneo Apr 23 '12 at 00:00

2 Answers2

3

If I understand correctly, you want the class value on your $target to correspond to an actual element on the page? Or instance, if target was:

<p id='foo' class='football'>Hello, World.</p>

You might have a corresponding element of:

<div id='football' class='games'>...</div>

You're asking how to use the className as the selector (specifically as an ID) during your appending:

var $target = $("#foo"); // reference to our paragraph
var targetClass = $target.attr('class');

$target.appendTo( '#' + targetClass );

This assumes that your class attribute will only ever hold one class. Class attributes can contain spaces, however if you tried to use one that contained spaces as an ID, you'd create a problem since ID values cannot contain spaces.

I'm assuming that if you wish to work it out like this, you've already kept that in mind.

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • I actually started writing the same solution, but you beat me by seconds, and must be something like this that the OP is after, +1. – adeneo Apr 23 '12 at 00:05
0

Use a class selector instead of an ID selector.

$target.appendTo($('.football'));

Jeremy Smith
  • 1,349
  • 8
  • 15