jQuery addClass() to element generated after append() - javascript

I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>

When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.

t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);

Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/

var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});

The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.

You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/

I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});

Related

jQuery Find and Replace all instances of part of a classname

I have several div's with a classname that looks like this:
class="col-md-4"
some have:
class="col-md-12"
What I want to do is to search for whatever the number at the end of the class is and replace all of them to:
class="col-md-6"
How can I do this using jQuery?
You can use special selectors in jQuery:
^= starts with ...
*= contains ...
Or use a combination of both selectors if you don't get them all.
var cols = $('[class^="col-md-"]');
Then to remove all classes with a wildcard
cols.removeClass(function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
});
Then add the class you want:
cols.addClass('col-md-6');
Try to remove the class and add the new one:
$(".col-md-4").removeClass("col-md-4").addClass("col-md-6");
$(".col-md-12").removeClass("col-md-12").addClass("col-md-6");
you can use "contains" selector like this
$("[class*='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");
removeClass function based on this answer
$("[class*='col-md-']")
will find any element with a class that contains col-md-.
The removeClass function will than remove it. And finally col-md-6 will be added.
EDIT
changed [class^='col-md-'] to [class*='col-md-'] in case class attribute has another class before col-md-. Thank you #dfsq for pointing this out
This should also work:
$('[class*=col-md]').removeClass('col-md-4 col-md-12').addClass('col-md-6');
You could do it with simple javascript if all of those elements were inside a main div.
For example:
var arr_divs = document.getElementById('main_div').getElementsByTagName('div');
for(var i = 0; i < arr_divs.length; i++){
if(arr_divs.item(i).className == 'col-md-12' || arr_divs.item(i).className == 'col-md-4'){
arr_divs.item(i).className = 'col-md-6';
}
}
This may not be the most efficient way of doing what you want but, it keeps it simple. Here's a working fiddle: https://jsfiddle.net/Lns1ob5q/
$("[class^=col-md-]").attr("class", "col-md-6");
The above selects all elements with a class containing col-md- ([class^=col-md-]) and replaces the class, regardless of what number immediately follows, with col-md-6.
The reason I say it's not efficient is becuase jQuery will initially pick up elements that already have a class of col-md-6 and replace their class with the same one... But hey, it works!

Toggle() an element by class name within a div

I'm trying to write a javascript/jquery function that looks inside a div with a specific ID and removes a specific class from any child div(s) with a specific class.
E.g. the function should remove the class removeme from any divs inside div id="foo":
<div id="foo" onClick="openGame('foo')">
<div class="bar removeme"></div>
</div>
My attempt at writing this function:
function openGame(divid) {
var container = document.getElementById(divid);
var responses = container.getElementsByClassName("bar");
while (responses[0]) {
responses[0].removeClass('removeme');
};
}
Please note I'm a super beginner in JS and not super familiar with while loops :/
If you want to use jQuery to achieve this.
$(document).ready(function() {
$('div#foo').click(function() {
$(this).find('.removeme').removeClass('removeme');
});
});
This creates a click event on your element with the id "foo" that will find every elements inside of it and remove the class "removeme" from it.
I would use JQuery for this job:
$("#foo").find("div").removeClass("removeme");
This will find all children of #foo and remove the class .removeme.

Getting ALL First links in a specific class

So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
Link 1
Link 2
</div>
<div class="masterclass">
Link 1
Link 2
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find(), it will find all the .masterclass elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
$(".masterclass a:first-child") is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
This is how u loop through each of the masterclass and get the first link of it.
i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index
http://jsfiddle.net/kBd82/6/
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

Add class name for generated Html using jquery

Below is html part
<li class="main_menu catagory_li" id="cat4">
<p class="ahead"><span class="heading">Item 4</span>
<span class="fright remove">close</span></p>
</li>
when i click close i copy the LI using below code,
$('.remove').live('click',function(){
var closed_elem_id = $(this).parent().parent().attr('id');
s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('li#'+closed_elem_id).remove();
console.log(s);
});
This one removes the LI in particular place and get the copy and store it in variable s.
My requirement is to add class called no-display in cloned copy like <span class="fright remove no-display">close</span> . I tried this many ways but it fails.
Kindly advice on this
NOTE : updated my question
A little optimized: http://jsfiddle.net/hKUd6/
Something like this:
$('.remove').live('click',function(){
var pLi = $(this).closest('li');
s = $('<div>').append(pLi.clone().addClass('no-display')).html();
pLi.remove();
console.log(s);
});
This whole thing is very sloppy. You don't need to use as much code as you have to accomplish the simple task you're attempting.
Try something like this:
$("li").on("click", ".remove", function(){
var $this = $(this),
liCont = $this.closest("p"),
parentLi = $this.closest("li");
liCont
.clone()
.wrap(
$("<div>").addClass("no-display")
)
.appendTo("body");
parentLi.remove();
});
What we do here is capture the click event on any .remove elements. We select the parent p (which we later clone to wrap with a div) as well as the parent li. We clone the p element (including its contents), wrap it with a div element (which we create using DOM scripting and add the class), and append the finished product to the body (you can change that if needed). We then remove the original li.
Try with this code, it should work:
$('.remove').live('click',function(){
var closed_elem = $(this).closest("li"); //get the li to be closed/removed
var clonedElem = closed_elem.clone().find("span.remove").addClass("no-display"); //clone the original li and add the no-display class to the span having remove class
closed_elem.remove(); //remove the original li
console.log(clonedElem);
});
Please check below lines of code.
first of all you need to get current class name using jquery:
$('li #cat4').find('span').each(function(){
var classname = $(this).attr('class');
$(this).addClass(classname+' no-display');
});
This is not a complete code of your task, but its just a code by which you can get a current class and then add more required string to it and set new class.
Thanks.

Categories