[jQuery] append id

Hi,

Still working on understanding the magic of jQuery :slight_smile:

I’m trying to click a <div>, get its id, and append it to a <p>.


 $(".test").click(function() {
     var id = this.id;
     id.appendTo("#ids");
   });


<p id="ids">
ids:
</p>

<div class="test" id="1"></div>
<div class="test" id="2"></div>

:slight_smile:

You’ve almost got it… :slight_smile:

Try this:


 $(".test").click(function() {
     var id = this.id; 
     $('#ids').append(id);
});

Thansk a lot :slight_smile:
I searched the jaQuery manipulation part of the manual, but unfortunately I didn’t find something like “toggleAppend”, which would let me add an id when I click, and remove it if I click again that element.

How would you go?

Thanks again :slight_smile:

Regards,

-jj.

The easiest wat would be to have another element which just takes the id number - this way we could just replace it’s entire content… So, if you were to use a span it would be like this:

HTML:


<p id="ids">
ids: <span id="idspan"></span>
</p>
    
<div class="test" id="1">THIS IS DIV 1</div>
<div class="test" id="2">THIS IS DIV 2</div>

JS:


$(".test").click(function() {
     var id = this.id;
     $('#ids span#idspan').html(id);
});

Hi,
Thank you for your reply. It’s a very interesting example :slight_smile: Makes me learn :slight_smile:

But I wasn’t very clear in my first post, sorry about that. When I click <div> number one, I’d like its id to be appended. When I click <div> number two, I’d like its id to be appended next to the first id already appended. And if I click again <div> number one, I’d like its id to be removed from the <p>#ids. Same goes for <div> number two.

In other words: there can be more than one id appended, but if an id is already appended, we remove it.

'Hope I’m clear :slight_smile:

Thanks again for your help.

Regards.

-jj.

Right ok… I understand… :slight_smile:

–>

JS:


$(".test").click(function(){
    var id = this.id;
    var spans = $("span[rel='id-" + id + "']");
    (spans.length !== 0) ? $("span[rel='id-" + id + "']").remove() : $('#ids').append('<span rel="id-' + id + '">' + id + '</span>');
});

I forgot to say that ID attribute values cannot start with numbers… They’ll work but if you want to comply to standards then don’t do it…

HTML:


<p id="ids">
ids: 
</p>
   
<div class="test" id="div1">THIS IS DIV 1</div>
<div class="test" id="div2">THIS IS DIV 2</div>

You rock Jimmy (as usual).

Could you explain to me this part?


span[rel='id-" + id + "']

Have a look here for an explanation -> http://docs.jquery.com/Selectors/attributeEquals#attributevalue

Glad I could help… :slight_smile: