Adding unique class name to dynamically created elements/ JS / jQuery - javascript

If I have ten divs created dynamically, each one given the class name 'createdDiv' on creation. How can I iterate through them after they are created and add a unique class name to each?
Somthing like,
for each('.createdDiv'){
var count = 1;
this.addClass('uniqueName' + count);
count ++;
}
So I would like to end up with 10 divs as follows,
('.createdDiv .uniqueName1')
('.createdDiv .uniqueName2')
('.createdDiv .uniqueName3')
('.createdDiv .uniqueName4')
and so on...

$('.createdDiv').each(function(i){
$(this).addClass('uniqueName' + i);
});

Try
$('.createdDiv').addClass(function (i) {
return 'uniqueName' + (i + 1)
})
Demo: Fiddle

$('.createDiv').each(function(i){
$(this).addClass('uniqueName'+ (i+1));
});

This is not exactly what you're asking for, but another way to later access a list of generated elements would be to use the data attribute:
$(".createDiv").each(function(i){
$(this).attr("data-index", i);
});
Then to select an element based on it's index:
$(".createDiv[data-index='" + i + "']")
Demo: Fiddle

Related

How to click to clone all id's that match these classes

I'm creating a page where I click a button and add content to a div. Right now I have three buttons that all have at least one class. Each class corresponds to a single div id that has its own content. What I'm trying to do is grab each class that is on the button, find the div id that has the same name, clone it, and append it to the #return div.
I have a working example that will only clone the first class name it sees on the button. How can I have my jquery find all div id's that match the classes on the button, clone them, and append them to #return?
These buttons can have the same class but when it's cloned in the #return, I don't want it cloned again. I have an if statement that tries to prevent this but it ends up deleting them. How can I stop this?
I have fiddle here that shows this jquery working:
$(document).ready(function() {
$("[id^=button]").click(function() {
var myclass = $(this).attr("class").split(" ");
if ($(this).is(".a1,.a2,.a3")) {
$("div#" + myclass).first().clone().appendTo("#return");
}
if ($("#return div#" + myclass).length > 1) {
$("#return div#" + myclass + ":last").remove();
}
});
});
The problem is that myclass is an array, so when you add that as a string to create a selector like "div#" + myclass it ends up creating a selector "div#a1,a2" which is not what you want.
You should iterate over the myclass array and perform your logic for each class.
Something like this
$(document).ready(function() {
$("[id^=button]").click(function() {
var myclass = $(this).attr("class").split(" ");
if ($(this).is(".a1,.a2,.a3")) {
myclass.forEach(function(currentClass) {
if ($("#return div#" + currentClass).length == 0)
$("div#" + currentClass).first().clone().appendTo("#return");
});
}
});
});
Updated demo at: https://jsfiddle.net/zyech6L3/2/
you need to iterate through to check what classes are available.
like:
for(var j=0; j<myclass.length; j++){
$("div#" + myclass[j]).first().clone().appendTo("#return");
}
see this fiddle:
https://jsfiddle.net/c4soamkr/

jQuery Selector equivalent of javascript

I am trying to get the jquery equvaliant of this javascript
var id = $(this).parent().parent().parent().attr("id");
document.getElementById(id).getElementsByClassName("addcomment")[0].style.display = 'block';
but its not working
$('#+id+' '.addcomment').css('display','block');
Any suggestions ?
$('#' + id + '.addcomment').css('display','block');
as a sidenote in the page you should have only one element with that id, so
$('#' + id ).css('display','block');
should works too (of course only if classname it's not necessary to target it, since this is a different selector)
$('.addcomment', '#' + id).css('display','block');
or just simple
$('#' + id).css('display','block');
I think you need to get the child elements based on their class. So try this.
$('#' + id ).find('.addcomment').show();

Give the classes a specific id

I have a question about the class, and give the class a specific id.
For example I've got a html code like this:
<div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
My question is how can I add an id by each .test class.
I thought something like this in Jquery:
var i = 1;
$('.test').each(function(){
$('.test').attr('id','id_'+i+'');
i++
});
This doesn't work I think it's something with .closest() or .next()
to solve this problem.
Regards,
Frank
EDIT:
I solved the problem by myself the answer is:
$('.test').each(function(){
$(this).attr('class','test').attr('id','id_'+i+'');
i++;
});
No reason to make a counter, .each() comes with one built in.
$('.test').each(function(i){
$(this).attr('id','id_'+i+'');
});
Use $(this) to refer to the current element the in callback function:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i);
i++
});
Much faster and simpler like this:
$('.test').each(function(i){
this.id = 'id_' + i;
});
There's no need for .attr() when setting or getting the id of an element.
Or if you wanted the numbers to start with 1, do this:
$('.test').each(function(i){
this.id = 'id_' + (i + 1);
});
You were on the right path:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i+'');
i++
});
Use this jQuery instead:
var i, $test = $('.test'), tl = $test.length;
for (i = 0; i < tl; i++) {
$test.eq(i).attr('id','id_'+i+'');
}
As i is incremented in the for loop, you select the specific element you want to give the i based id with .eq(i).

Numbering in jQuery

How could I change the text below so that the text within it has a number appended to it.
<div class="right">This is some text</div>
<div class="right">This is some text</div>
<div class="right">This is some text</div>
So the code above would become,
This is some text
This is some text
This is some text
you should use an ordered list... ol
or else you will need use css and add the content property your selector with the :after pseudo element.
How about the following?
$("div.right").each(function(i){
$(this).prepend((i + 1) + ". ");
});
UPDATE:
Here is one way that should work.
"number" is a custom element (it can be anything you want) that will/should be ignored by browsers.
$("div.right").each(function(i){
$(this).find("number").remove().end()
.prepend("<number>(i + 1) + ". </number>");
});
OR use the following which is probably a little slower but semantically correct...
$("div.right").each(function(i){
$(this).find("span.number").remove().end()
.prepend("<span class='number'>" + (i + 1) + ". </span>");
});
OR an even better way would be to prepend span.number before your first drag:
$(function(){ // document ready...
// caching the "numbers" will only work if you use the DOM
// for updating div position (like jQuery's "append()", "prepend()", "before()", and "after()") and not "innerHTML" or "html()"
var numbers = $("div.right").each(function(i){
$(this).prepend("<span class='number'>" + (++i) + "</span>. ");
}).find("span.number");
function dragEnd(){
// do your drag end stuff here...
numbers.each(function(i){
this.innerHTML = ++i;
});
)};
});
This is really an elaboration on another comment. I can't format code in a comment, I guess. You could use jQuery core's each:
$('div.right').each(function(ii){
html = $(this).html();
$(this).html(ii + '. ' + html);
});
jQuery selectors are your friend...
Get your stuff and loop on through something like this:
texts = $("div.right");
for(i = 0;i < texts.length;i++)
{
node = $(texts[i]);
content = node.html();
number = i + 1;
node.html(number + ". " + content);
}
Update: Jeez, last time post untested code straight off the dome here (disclaimer: not actually the last time). In the interest of correctness, I've updated it to at least run (and work!) if you still want to do it this way. Although I admit the other solutions are cleaner and more elegant.
Does this have to be done dynamically through jquery? Can't you just combine all that text into one div and then make a ordered list around it?
Using [] notation with a result set will give you the raw DOM element which does not have the html() function. Use the eq() function to get each element wrapped in a jQuery object.
You can also use each() as mentioned above, but I prefer straight 'for loops' so I don't have to adjust for 'this' if I'm in an event handler.
var texts = $("div.right");
var elem;
for(i = 1; i < texts.length; i++) {
elem = texts.eq(i);
html = elem.html();
elem.html(i + '. ' + html);
}

jQuery: Pass variable to :eq() does not work

I have been trying to find out why the following lines of code do not work:
$('#add-cloud > select').change(function() {
var selected = parseInt($('#add-cloud select option:selected').val());
$("#cloud-calculator table tr:eq(selected)").css("color", "red");
});
If I change :eq(selected) to :eq(4) for example - works fine. How do you pass variable as an argument to :eq() ?
You have to concatenate your variable with your selector:
$("tr:eq("+selected+")");
The way you're doing it, you're embedding the actual string "selected" in the selector. You need to construct a string using your selected variable as a part of it:
$("#cloud-calculator table tr:eq(" + selected + ")").css("color", "red");
Also, you can simply use the 'this' object to get the seleted value.
$('#add-cloud > select').change(function()
{
var rowSelector = '#cloud-calculator table tr:eq(' + parseInt(this.val()) + ')';
$(rowSelector).css("color", "red");
}
Yes we can pass variable to eq() function. But you need to disable Firebug. Otherwise it wont work.
Please check this example.
var index = 3
$('#sidebar_menu li:eq('+index+')').css({"color":"#050959"});

Categories

Resources