Remove all span elements by classname? - javascript

I have a classname called notag. When i click a button, it triggers my onclick event to call my function. Within the function i want it to remove / delete all span elements that has that classname notag.
My attempts are below but no luck! Please help thanks.
onclick="replaceQueuePlaylist()"
function replaceQueuePlaylist()
{
$("span").attr('notag').remove(); //dont work
$('.notag').remove(); //also dont work
}

$("span").attr('notag').remove(); //dont work
This won't work because your elements have a class named notag, and not an attribute. class itself is an attribute with value notag in <div class='notag'> hello world </div>
There's no need to explicitly use .each() as using $(selector).remove() will automatically iterate through each element with the selection criteria and remove it.
$('#delete-em').on('click', function(){
$('.delete-me').remove();
});
.delete-me{
height: 50px;
width: 50px;
margin: 5px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='delete-me'></div>
<div class='delete-me'></div>
<div class='delete-me'></div>
<div class='delete-me'></div>
<button id="delete-em">Remove</button>

With jQuery.remove() you can directly remove all the set of matched elements from the DOM:
function replaceQueuePlaylist() {
$('span.notag').remove();
}

Try this one;
function replaceQueuePlaylist() {
$("span.notag").each(function () {
$(this).remove();
});
}
Finds all the spans with notag class name and delete them.

Just add these lines in your function. Happy coding
$("span.notag").each(function () {
$(this).remove();
});

Related

I need to remove a class after adding it clicking on same checkbox, not the document

I'm clicking on a checkbox to add some animation to a div, but when I want this animation to disappear I can only make it happen through $(document) click. Checkbox must add and then remove the class.
JS
$('#inOrder').click(function(e) {
$('.border').addClass('colorsborder');
e.stopPropagation();
$(document).click(function(e) {
$('.border').removeClass('colorsborder');
});
});
$('#inOrder').click(function(e) {
e.stopPropagation();
});
HTML
<input id="inOrder" type="checkbox" />
You may call toggleClass() method on the jQuery object (element) that you want to add or remove the class from. The method toggleClass will either:
add the desired class when the element doesn't have it.
or remove that class when the element has it already.
Here's a basic, live demo to illustrate the functionality:
const checkbox = $('#inOrder'),
relatedDiv = $('#related');
checkbox.on('change', () => relatedDiv.toggleClass('custom'))
/** just for demo purpose */
#related {
margin: 15px 0;
padding: 10px;
border: 1px solid #ccc;
}
#related.custom {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inOrder" type="checkbox" />
<div id="related">My appearnace will change on checkbox click</div>
The above demo is pnly meant as a showcase of a possible solution that could be applied to your current problem and it WON'T do the exact thing you want to have unless you apply the required changes you need to suit your actual code/structuring.
Then you want to toggle the class not add it when you click on checkbox
$('#inOrder').click(function(e) {
$('.border').toggleClass('colorsborder');
....

Can't hide other elements while clicking on another

I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}

Add active class to next sibling

Could someone help me with this, I am a bit stuck with JavaScript. Every time when someone is clicking on the question, the active class name should be added to the next sibling, but how to get that fixed. Only in plain JavaScript please. Any other frameworks do not count.
document.querySelector(".question").addEventListener("click", function() {
if(this.classList.contains("active")) {
this.classList.remove("active");
} else {
this.classList.add("active");
}
});
.faq-block .question,
.faq-block .answer {
border: 1px solid red;
padding: 10px;
}
.answer {
display: none;
}
.active {
display: block;
}
<div class="faq-block">
<div class="question">How do I cancel my order</div>
<div class="answer">Answer</div>
</div>
<div class="faq-block">
<div class="question">I am not getting an internet connection from my second SIM card</div>
<div class="answer">Answer</div>
</div>
<div class="faq-block">
<div class="question">My charger does not work and my device would not charge properly</div>
<div class="answer">Answer</div>
</div>
<div class="faq-block">
<div class="question">My fingerprint scanner is not working and does not respond when touched</div>
<div class="answer">Answer</div>
</div>
Use querySelectorAll ,document.querySelector will only select first matched element.
// get all matched element
var ques = document.querySelectorAll(".question")
// loop over the array to add event to each of the element
ques.forEach(function(item, index) {
// creating closure
(function(i) {
// adding event listerner to each element
ques[i].addEventListener("click", function() {
// this refers to the current selected element
if (this.classList.contains("active")) {
this.classList.remove("active");
} else {
this.classList.add("active");
}
});
}(index)) // passing the index to target element in the array
})
DEMO
Try this
document.querySelector(".question").addEventListener("click", function() {
if(this.classList.contains("active")) {
this.classList.remove("active");
this.nextSibling.classList.add("active")
} else {
this.nextSibling.classList.add("active");
}
});
I don't know why u need to do conditional checking. but to answer your question, you can use nextSibling
A simple adjustment to your CSS will do the trick:
.question.active+.answer {
display: block;
}
This will allow you to set the "active" class on the question, and let it reveal the answer.
Alternatively, use this.parentNode for the class, and then the CSS becomes:
.faq-block.active>.answer {
display: block;
}
This, I would argue, conveys more meaning too.
First of all document.querySelector(".question") returns the first element matching selector(documentation).
If i understood right you wanted to get .active class applied to Answers so here you are:
document.querySelectorAll(".question")
.forEach(element => element.addEventListener("click", function () {
nextNode = this.nextElementSibling;
if(!nextNode.classList.contains("active")){
nextNode.classList.add("active");
}
else{
nextNode.classList.remove('active');
}
})
);
JSFiddle

Jquery will not select button after class has been toggled

I have some jquery that will, when a button is clicked, switch a class from a button to a different class (i.e. on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.
https://jsfiddle.net/myfb44yu/
This is the problematic javascript.
$(document).ready(function(){
$('.first').click(function(){
alert('works');
$('#testButton').toggleClass('first', 'second');
});
$('.second').click(function(){
alert("works");
$('#testButton').toggleClass('second', 'first');
});
});
The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.
Your main issue here is a syntax error in regards to your .toggleClass, but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.
An overview of jQuery Event Bindings
Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.
The toys in this example would be your .first and .second elements.
This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.
So, if you do $('.myClass').click();, then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.
Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event.
The Solution
$(document).on("click", ".first", function() { } );
This is known as event delegation.
In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.
Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first.
Hope this helps.
EDIT: As I was typing, JHecht left a good answer that points out the same issue I outlined above.
N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working.class selector
Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second
instead you can write as following
check this snippet
$(document).ready(function() {
var firstElements = $('.first')
var first = firstElements[0];
var secondElements = $('.second');
var second = secondElements[0]
$("#testButton").click(function() {
alert('works');
$(this).toggleClass('first').toggleClass('second');
});
});
.first {
color: red;
}
.second {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
Hope it helps
Ho about this solution. Hope it helps!
$(document).ready(function(){
$("#testButton").click(function(){
if($(this).prop("class") === "first"){
alert('first');
$(this).removeClass("first").addClass("second");
}
else if($(this).prop("class") === "second"){
alert("second");
$(this).removeClass("second").addClass("first");
}
});
});
.first{
color: red;
}
.second{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
I hope that what I am about to say makes more sense than I feel it does.
Your issue is that when you assign the click events, there is not currently an element that has a class of .second.
Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.
A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.
$(function() {
$(document).on('click', '.btn-first,.btn-second', function() {
//here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
//Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
$(this).toggleClass('btn-first btn-second');
});
});
.btn {
padding: 4px 8px;
border-radius: 3px;
border: 1px solid grey;
}
.btn-first {
background-color: green;
border-color: green;
}
.btn-second {
background-color: orange;
border-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='btn btn-first'>Hi</button>
</div>
A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.
$(document).ready(function(){
$('.first').click(function(){
$('#testButton').toggleClass('first second');
});
$('.second').click(function(){
$('#testButton').toggleClass('first second');
});
});
.first { border: thick outset green;}
.second { border: thick inset red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="first">This paragraph has first class</p>
<p class="second">This paragraph has second class</p>
<button type="button" id="testButton" class="first">this button starts out first class</div>
The script can then be simplified by combining multiple class names in a single selector, leaving just:
$(document).ready(function(){
$('.first, .second').click(function(){
$('#testButton').toggleClass('first second');
});
});
Make a neutral class that the buttons both share (.btn).
Then add one of the state classes to each button (.first or .second).
Delegate the click event to the neutral class only ($('.btn').on('click',...).
Then toggle both state classes on this ($(this).toggleClass('first second');)
The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
There is an example with the images outside of buttons and another example that doesn't toggle classes around.
SNIPPET
$('.btn').on('click', function() {
$(this).toggleClass('first second');
});
/* OR */
$('.alt').on('click', function() {
$('.img').toggle();
});
.first > .one {
display: block;
}
.first > .two {
display: none;
}
.second > .one {
display: none;
}
.second > .two {
display: block;
}
.first + .one {
display: block;
}
.first + .one + .two {
display: none;
}
.second + .one {
display: none;
}
.second + .one + .two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Use jQuery with CSS</p>
<button class='btn first'>
<img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<button class='btn second'>
<img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<br/>
<br/>
<button class='btn first'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<button class='btn second'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<p>Or use only jQuery no CSS</p>
<img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
<img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
<button class='alt' style='display:block;'>Toggle</button>

Javascript addClass removeClass not working as desired

When I click on the icon, I want it to be switched on/off.
In my html file I have:
<div class="startSharing"></div>
And in my js:
$('.startSharing').click(function() {
$(this).removeClass('startSharing');
$(this).addClass('stopSharing');
});
$('.stopSharing').click(function() {
$(this).removeClass('stopSharing');
$(this).addClass('startSharing');
});
It works fine when switching from on to off - but I don't understand why it still goes into "startSharing" section when it is turned off.
Thank you for help.
In this case, you're setting the handlers to the particular elements. Once they're set - they're set, regardless of the selector changing.
You could just define it on the .startSharing element, if they all start like that. Then, you could use .toggleClass() to easily switch them on/off:
$('.startSharing').click(function() {
$(this).toggleClass('startSharing stopSharing');
});
You may also delegate the click event like this:
$('body').on('click', '.startSharing', function() {
$(this).removeClass('startSharing').addClass('stopSharing');
});
$('body').on('click', '.stopSharing', function() {
$(this).removeClass('stopSharing').addClass('startSharing');
});
Doing it this way will also allow dynamically-generated to trigger events. In your case, .stopSharing was generated dynamically.
use event delegation
$('#container').on('click',".startSharing,.stopSharing",function(){
$(this).toggleClass('startSharing').toggleClass('stopSharing');
});
#container div {
width: 250px;
height: 100px;
}
.startSharing {
background-color: green;
}
.startSharing::after {
content: "start sharing";
}
.stopSharing {
background-color: red;
}
.stopSharing::after {
content: "stop sharing";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="startSharing"></div>
</div>

Categories