Thansk a lot
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.
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 Makes me learn
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.
$(".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>