How to add a class when a link has a certain label - javascript

I have a series of links with no a classes. I am unable to manually add any classes in the HTML...otherwise I would. I want to use either JavaScript or jQuery to detect a certain link label and add a class to it if the match is found.
Here is the HTML:
<ul class="menu-main-nav">
<li>Duck</li>
<li>Duck</li>
<li>Goose</li>
</ul>
I want to add a class whenever "Goose" appears. Here is what I attempted... and failed.
$(document).ready(function(){
if ($("#menu-main-nav li a").text() == "Goose") { this.addClass("itsagoose")};
});

Use the .filter method:
$("#menu-main-nav li a").filter(function(){
return $(this).text() == "Goose"; //<--- Only include these elements
}).addClass("itsagoose");
Use .html() instead of .text() if you want an exact match, and don't want to allow anything else (eg, don't match <a><span>Goose</span></a>).
Fiddle: http://jsfiddle.net/RWSCY/

Look at the jQuery contains selector. That's what it's for :)

Well, you could use filter:
Demo
$("a").filter(function(){
return $(this).text() == "Goose"
});

Related

remove some elements if no children

i need to remove some elements if no children...
this will work...
$$('*').each(function() {
($$(this).text().trim() === '') && $$(this).remove()
});
but it will look for all elements... i need to limit to some elements.. so i made this..
elements.forEach(element => {
$$(element).each(function() {
($$(this).text().trim() === '') && $$(this).remove()
});
})
but it doesn't work..
You can use :empty pseudo selector to collect all the empty elements:
$(':empty').remove(); // removes all the empty elements
If you target some specific elements then either give it a class name and use both in conjuction:
$('.theClass:empty').remove();
Or just use the tagnames of specific elements:
$('div:empty').remove(); // removes all the empty divs
You can use the id, classor tag in the jQuery selector. Try the following way:
$("div:empty").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div><span>test</span></div>
<div></div>
I like Mamun's approach. If you want to apply it on a certain collection of element types only you could modify/simplify it as such:
$("div,td,p,... and other elements").filter(":empty").remove();
Sorry, just noticed, that Jay also provided a part of my solution. I did not want to repeat things unecessarily here, but maybe the combination of the two is still relevant.
Remove all empty tags from current document
$("*:empty").remove();
If I understood correctly what you asked, you should rty :
if($("some selection").children() === undefined){
//do something
}
or as a function :
function rmIfNoChild(jQobj){
if(jQobj.children() === undefined){
//do something
}
}

Jquery remove element

I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.
var buttonSelect = $(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append(this.value + " ")
}
else {
$(".list").remove(this.value)
}
});
You should rather append the content along with html element like span:
$(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{
$(".list").find('.newval_'+this.value).remove();
}});
The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:
<li class="list">test</li>
Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:
$(".list").remove(":contains('"+this.value+"')");
If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.
$(document).ready(function() {
$("button").click(function() {
$("div").remove(); //remove Div element
});
});
You can see an example here: How to Remove Elements from DOM in jQuery

How to find anchor without a specifc class using jquery?

I want to remove anchors with href contains "#tab" without a specific css class "atitleTabs" from some specific divs whose Id contains "tab". I have tried the following code it didn't work for me.
$(window).load(function () {
$('div ul li a').filter(function () {
if (!$('div ul li a').hasClass('atitleTabs')) {
alert('Got Anchor without the particlauar class');
alert($('div ul li a').attr('href'));
} else {
alert('Got Anchor with class');
}
});
});
How can i do it, please help me, how can i achieve my goal.
Try to use attribute contains selector to achieve what you want,
$('div[id*="tab"] a[href*="#tab"]:not(".atitleTabs")').remove();
or just try the samething with .filter()
$('div[id*="tab"] a[href*="#tab"])').filter(':not(".atitleTabs")').remove();
You can use attribute contains selector:
$('[id*="tab"]').find('[href*="#tab"]').remove();
Try
$("[id*=tab]").find("[href*='#tab']").remove();
You can use attribute selector * for this purpose.
If you want to use startwith clause you can use ^.
If you want to use endswith clause, use $

Find element above another using jQuery

I'm trying to find the element using jQuery from the following html.
<ul class="gdl-toggle-box">
<li class="">
<h2 class="toggle-box-title"><span class="toggle-box-icon"></span>Volunteer Form</h2>
<div class="toggle-box-content" style="">
</div>
</li>
</ul>
What I'm looking to do is when the h2 is clicked find the li above the h2 add a class active to it. Tried a few different calls but no luck.
EDIT
The biggest issue is that there are multiple toggle boxes on a page so something like this works on pages with a single toggle but pages with multiple the result is they all open together.
var gdl_toggle_box = jQuery('ul.gdl-toggle-box');
gdl_toggle_box.find('li').each(function(){
jQuery(this).addClass('item');
});
gdl_toggle_box.find('li').not('.active').each(function(){
jQuery(this).children('.toggle-box-content').css('display', 'none');
});
gdl_toggle_box.find('h2').click(function(){
if( jQuery('.item').hasClass('active') ){
jQuery('.item').removeClass('active').children('.toggle-box-content').slideUp();
}else{
jQuery('.item').addClass('active').children('.toggle-box-content').slideDown();
}
});
You can use closest.
closest will match the first parent element that matches the selector traversing up the DOM tree.
Demo
$('h2.toggle-box-title').click(function(){
$(this).closest('li').addClass('active');
});
Try this.
$('h2.toggle-box-title').click(function(){
$(this).parent().addClass('newclass');
});
try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
On you click in the button you can use the event:
$("something").parent().find("h2.myClass");
// And if you want you can add class after you find you object
http://api.jquery.com/find/
Selecting an element's parent
In order to select an element parent, you can use the parent() function.
Try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
*to be more specific, you target the parent you would like to choose by specifying its selector
Check the jQuery API Documentation here
parent() - Get the parent of each element in the current set of matched elements,
optionally filtered by a selector.

using jquery, how do I check if an element is visible or not?

I also need to find out all the elements inside a div, and check for their visibility. How to do it?
The first part of your question sounds like you want to find all the elements inside of a div. And then check for visibility.
To get all elements that are descendants of a div, use:
$('#myDiv *')
So to test each element, and act accordingly based on visibility:
$('#myDiv *').each(function() {
if( $(this).is(':visible') ) {
// code to run if visible
} else {
// code to run of not visible
}
})
You can select them using the :visible and :hidden pseudo-elements. For example, selects all the visible descendants of a <div>.
$("div :visible")...
Of you can do a test using is(). For example:
if ($("#someId").is(":visible")) { ...
$('#myElement').is(':visible');
Will return true or false
Use the :hidden and :visible selectors.
$("div:visible").hide();
$("div:hidden").show();
use the $(div :visible) selector to select all visible elements in the div. you may loook at http://api.jquery.com/visible-selector/ for more details.

Categories

Resources