Add class to last div in lists using jQuery - javascript

If I have this list...
<div class="class1">
<div class="class2">
<div class="class3">
<span class="class4">test</span>
</div>
</div>
</div>
<div class="class1">
<div class="class2">
<div class="class3">
<span class="class4">test</span>
</div>
</div>
</div>
<div class="class1">
<div class="class2">
<div class="class3">
<span class="class4">test</span> <--- Add class5 here in addition to class4
</div>
</div>
</div>
How do I add class2 in the correct spots? I need it to add to the last span every time even though the number of spans will change. I have something like this, but it doesn't account for the number of items in the list.
jQuery(".class4)").addclass("class5");
Is there anyway to do a "last" class4 scenario? Any help would be appreciated.

Use
jQuery('.class4').last().addClass('class5');

Use last:
jQuery('.class4').last().addClass('class5');

You can use :last
http://api.jquery.com/last-selector/
$(".class4:last").addClass("class5");

Use the last selector of jQuery
http://api.jquery.com/last-selector/
$(".class4:last").addClass("class5")

There is a stray closing parenthesis after .class4 in your selector:
jQuery(".class4").addclass("class5");
This still does not work because addClass is case sensitive[1]:
jQuery(".class4").addClass("class5");
But to target only the last .class4 you can use the :last pseudo-selector[2]...
jQuery(".class4:last").addClass("class5");
... or the .last() jQuery method[3]:
jQuery(".class4").last().addClass("class5");
[1] http://api.jquery.com/addClass/
[2] http://api.jquery.com/last-selector/
[3] http://api.jquery.com/last/

Related

Removing div's and keep content

I'm trying to remove the following DIV's:
<div class="whatever_name">
<div class="whatever_name">
<h2>subtitle</h2>
<p>content<p>
</div>
</div>
and need the following output:
<h2>subtitle</h2>
<p>content<p>
Using jQuery, I can not use remove() because it clear the content too. With pure javascript, happens the same.
I have no idea how to accomplish this issue.
Any idea?
EDIT:
Not always the structure is the same. It can vary, i.e.:
<div class="whatever_name">
<div class="whatever_name">
<div class="whatever_name">
<h2>subtitle</h2>
<p>content<p>
</div>
</div>
</div>
Just need an iterator that can handle such task.
Use unwrap() method twice on the children element.
$('.content .post-12')
// get children elements, or use contents()
.children()
// use unwrap twice to unwrap two parents
.unwrap().unwrap()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="post-12">
<h2>subtitle</h2>
<p>content</p>
</div>
</div>
UPDATE : With the updated content you just need to change the selector with your requirement.
$('div > div > h2,div > div > p').unwrap().unwrap()
// or use
// $('div > div:has(h2):has(p) > *')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="whatever_name">
<div class="whatever_name">
<div class="whatever_name">
<h2>subtitle</h2>
<p>content
<p>
</div>
</div>
</div>

if one item is clicked, remove the other items?

I'm learning Javascript and jQuery and I'm stuck at this one problem. Let's say my code looks like this:
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Now, if i click one of the div's, i want the other ones to disappear.
I know, I could create 4 functions for each one of them with on.click hey and display none with how , are and you. But is there a easier way? I bet there is, with classes maybe?
Thanks for responding!
Use siblings to get reference to its "brothers".
Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.
$('div').click(function(){
$(this).siblings().hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Or you can hide all the other div which not the clicked element using not
Remove elements from the set of matched elements.
$('div').click(function() {
$('div').not(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
You can just hide siblings() of clicked div.
$('div').click(function() {
$(this).siblings().fadeOut()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey">hey</div>
<div id="how">how</div>
<div id="are">are</div>
<div id="you">you</div>
Yeah there are some easier ways and I could tell a one from it,
Set a common class to all the elements that you are gonna target,
<div class="clickable" id="hey"> hey </div>
<div class="clickable" id="how"> how </div>
<div class="clickable" id="are"> are </div>
<div class="clickable" id="you"> you </div>
And you have to bind a single click event by using a class selector,
$(".clickable").on("click", function(){ });
Now use the .siblings() functions to hide the required elements,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").hide();
});
But using a toggle instead of hide would sounds logical,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").toggle();
});
Since you can do the same operation over all the elements.
You can use not to avoid element and this will indicate current instance.
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).hide("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Assign a class to each of the elements:
<div id="hey" class='sth'> hey </div>
<div id="how" class='sth'> how </div>
<div id="are" class='sth'> are </div>
<div id="you"class='sth' > you </div>
And write a js function onclick.
Remove class 'sth' from 'this' element in this function
Hide all elements with class 'sth' $('.sth').hide();
For this example - you don't need to add any further selectors to target the div's although in reality - this solution wwould cause all divs on the page to be affectecd - adding classes would be my actual suggestion: - but this works for this example. Click a div and all divs are hidden then the clicked one is shown. I also added a reset button to allow all divs to reappear.
$('div').click(function(){
$('div').hide();
$(this).show();
});
$('#reset').click(function(){
$('div').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
<hr/>
<button type="button" id="reset">Reset</button>
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).toggle("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>

How to remove last element from div?

I have list of descriptions and after remove one of them, I'd like to remove last element from div, not refreshing site. I don't know javascript in fact, so I'd like to ask how should my destroy.js.erb looks like? I can refresh whole class "descriptions" using
$('.descriptions').load(location.href + " .descriptions");
but I'm interested, if there is way to remove only last element.
<div class="descriptions">
<%= render #descriptions %>
</div>
//_description.html.erb
<div class="description-field">
<%= #description.text %>
</div>
Thank you for any help
<div class="parent">
<div class="child">
Item 1
</div>
<div class="child">
Item 2
</div>
<div class="child">
Item 3
</div>
</div>
The following line of jQuery would delete "Item 3."
$('.parent').children().last().remove();
Use css selector :last-child to remove it (found here). Then use jQuery to remove last element.
$(".yourdiv :last-child").remove();
Here is jsFiddle example:
html:
<div>
<p> Hello </p>
<p> World </p>
<p> last element </p>
</div>
JavaScript:
$("div :last-child").remove();
Use this if you want to remove the last div:
$("div:last").remove();
Use this if you want to remove the last sibling of some div with id "#mydiv"
$('#mydiv:last-child')
<div id="parent">
<div id="child">
Item 1
</div>
<div id="child">
Item 2
</div>
<div id="child">
Item 3
</div>
</div>
The following is a JQuery code that removes the last child item 3
$("#child").remove();
or you can also use
$("#child").css({"display": "none"});

Write a jQuery selector to filter the child divs having no subclasses

Consider the following HTML
<div class="container">
<div class="item medium type"> value1 </div>
<div class="item"> value2 </div>
<div class="item large"> value3 </div>
<div class="item small"> value4 </div>
<div class="item"> value5 </div>
<div class="item"> value6 </div>
<div class="item"> value7 </div>
<div class="item medium"> value8 </div>
<div class="item"> value9 </div>
</div>
Is there a straightforward way to write a jQuery selector to get all the children of the container div which does not possess any subclasses ?
For example, I need to write a selector ($('myselector').each()) and get only the item divs with values value2,value5,value6,value7,value9 (as these divs don't have any subclasses).
May be I am missing the obvious. But I did a quick search to get little information on this.
You can use this selector:
$('.container [class=item]')
It get every child with a class attribute exactly equal to item (so there is no other class).
But it's not really scalable, what if you need to add another class that don't exclude the element?
Maybe you should consider adding a class to other elements like:
<div class="container">
<div class="item sub medium type"> value1 </div>
<div class="item"> value2 </div>
<div class="item sub large"> value3 </div>
<div class="item sub small"> value4 </div>
<div class="item"> value5 </div>
<div class="item"> value6 </div>
<div class="item"> value7 </div>
<div class="item sub medium"> value8 </div>
<div class="item"> value9 </div>
</div>
And then use :not in your selector:
$('.container .item:not(.sub)')
You can use $("div[class$='item']")
Also you may take a look at http://api.jquery.com/category/selectors/
If you use the attribute selector like this:
$('.container [class=item]')
then it will only match an element that is exactly like this:
<div class="item">value1</div>
and not this (notice the whitespace around the class name "item"):
<div class=" item ">value1</div>
It is not safe to assume that there will never be whitespace in the class attribute. It's possible that whitespace gets inserted or left behind as the result of some jQuery DOM manipulation. A solution to this would be to trim the class attribute before selecting all elements with only the class "item".
$('.container')
.children() // select all the elements contained within .container
.each(function(){
// strip whitespace from class attribute
$(this).attr('class',$.trim($(this).attr('class')));
});
// fade out all elements within .container that ONLY have the class
// "item" and nothing else
$('.container [class="item"]').fadeOut();
try not
$('.container .item').not('.medium , .large,.small,.type')
or the attribute selector
$('.container [class=item]').each(function(){
//do your stuff
});

How should I edit strings across many instances of the same html?

I've got this code below, with different data, repeated over 10 times on the page I am working on:
HTML:
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
I want to alter the number in div.strong p (311) based on the number in div.kpaGraph p (43%) in the same manner across all instances of this code with Javascript/ jQuery. What is the cleanest way to do this? Should I select all $('div.kpaGraph p') and then use each() Or should I create a function and run it on all of them?
Thanks!
You can use the following to find the proper element in conjuntion with an .each() on $('div.kpaGraph p'):
$(this).parent().next('div.kpaBottom').find('div.strong p')
For example, using the following will take the value in the kpaGraph p node and append it to the p node in the following kpaBottom node:
$('div.kpaGraph p').each(function () {
$(this).parent().next('div.kpaBottom').find('div.strong p').html('foo');
});
jsFiddle example
There are a few ways.
You can use "next".
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).next('.kpaBottom .strong p');//this is the elm that has 311
});
Or you have to somehow create a relation between them so you know they go together, like a common parent.
<div class="kpaWr">
<div class="kpaGraph">
<p>Target: 43%</p>
<div class="progress">
<div class="bar"></div>
</div>
</div>
<div class="kpaBottom">
<div class="strong">
<p>311</p>
</div>
<div class="weak">
<p>number of teachers trained</p>
</div>
</div>
</div>
Then with jQuery you can select it like so:
$('.kpaGraph').each(function(){
var $kpaStrong = $(this).closest('.kpaWr').find('.kpaBottom .strong p');//this is the elm that has 311
});
Something like this might be pretty clean too:
$("div.strong p").text(function(index, text){
return $(this).closest("div.kpaBottom").prev("div.kpaGraph").find("p").text();
});
That would change the text to Target: 43% in your example.

Categories

Resources