remove some elements if no children - javascript

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
}
}

Related

jQuery if div has no any class or div

There is a duplicated <div class="content" data-num="2"></div> (would be more if click the button more times)which has got nothing in it.
How to check if content has nothing in it and get it removed ?
if($('.content').children().length == 0)
or need to use each something like?
$('.content').each(function(i, obj){
if($('.content').children().length == 0){
$(this).remove();
}
});
You can use the :empty jQuery selector which will select all elements that have no children. See http://api.jquery.com/empty-selector/ for details.
Using :empty will prevent the need for extra if checks in your loop - your delete function only operates on the items to delete ... much more efficient.
So something similar to:
$('.content:empty').each(function() {
//Do your delete, etc here :)
$(this).remove();
});
As suggested by jfriend00, the further simplification to just do a delete would be:
$('.content:empty').remove();
Lots of different ways to tackle it.
There is probably a simpler way to do this, but checking the html() of each .content should work for you. Demo
$(".content").each(function(i, obj) {
if($(this).html() == '') {
$(this).remove();
}
});
You've an extra ) which accidentally closing your if clause:
if($('.content')).children().length == 0){
// ------------ ^ remove this
Otherwise, your code with each() should work.

event if only one div has class

i have lots of divlayers with the class named ".current". depending on what the user does some of remove the class and some will get it again. this works fine, but what i want to is fire an event if only one div layer has the class ".current". how can i detect if only one element has the class current?
for example
if ($('#div4').hasClass('.current')) {
alert("fire me something");
}
something like "is the only one" hasClass.
in your event callback, simply check the number of divs that have the current class:
if ($('#div4').hasClass('current') && $('div.current').length === 1) {
...do stuff...
}
If you're only ever using current on divs, then you could just use $('.current').length === 1.
you should be able to use the css class as the selector and then get the length:
if($(".current").length == 1 ) {
alert('fire me something');
}
I "think" you could do:
if($('.current').length == 1) { //DO }
I believe the selector will return an array of the elements.
You have error syntaxe! you should add an ")" for your condition. and dont use the calss selecotr (".") . that's will work:
if($('#div4').hasClass('current')){
alert("fire me something");
}
You could see how many instances of the class .current that there are by using length. e.g.
var mycount = $(".current").length;
alert(mycount);
Then do whatever you like with the result.
See http://api.jquery.com/size/ or http://api.jquery.com/length/
$(".current").length
$(".current").size() *deprecated as of v1.8
Either will give you the count. Anytime you adjust the class check to see the count and fire the action if its 1

Detect an element inside a div using jQuery

What is the best way in your experience to detect the existence of an element inside a div?
I'm currently using this:
if (($('.parentDiv').width()) > 0){
//Do something
}
There has to be a more elegant way.
If empty means not even text nodes:
if ($('.parentDiv').contents().length){
//Do stuff
}
or:
$('.parentDiv:not(:empty)') // which is nice...
.contents docs:
Description: Get the children of each element in the set of matched elements, including text and comment nodes.
if you care only of elements and not text nodes:
if ($('.parentDiv').children().length){
//Do stuff
}
Probably not what you want, but considering there's at least a little confusing over your requirements, you could consider if anything at all is within the container: elements, text, whatever.
Say you have an empty div:
<div class="parentDiv"></div>​
Then $(".parentDiv").html().length == 0 indicates its emptiness.
If the div is not empty:
<div class="parentDiv"> </div>​
<div class="parentDiv"><div></div></div>​
Then $(".parentDiv").html().length will indicate its occupiedness (returning 1 and 11, respectively, in those scenarios.)
If you wish to check only for elements, or specific elements, then $(".parentDiv").children() would be the way to go.
Assuming you only care about elements (and not text nodes), you could check to see if the element has any children:
if($('.parentDiv').children().length) {
//Do stuff
}
Use the children() function
$('.parentDiv').children()
if ( $( '.parentDiv' ).children().length > 0 )
{
// do something
}

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

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"
});

Check if element is a div

How do I check if $(this) is a div, ul or blockquote?
For example:
if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
Something like this:
if(this.tagName == 'DIV') {
alert("It's a div!");
} else {
alert("It's not a div! [some other stuff]");
}
Solutions without jQuery are already posted, so I'll post solution using jQuery
$(this).is("div,ul,blockquote")
Without jQuery you can say this.tagName === 'DIV'
Keep in mind that the 'N' in tagName is uppercase.
Or, with more tags:
/DIV|UL|BLOCKQUOTE/.test(this.tagName)
To check if this element is DIV
if (this instanceof HTMLDivElement) {
alert('this is a div');
}
Same for HTMLUListElement for UL,
HTMLQuoteElement for blockquote
if(this.tagName.toLowerCase() == "div"){
//it's a div
} else {
//it's not a div
}
edit: while I was writing, a lot of answers were given, sorry for doublure
Going through jQuery you can use $(this).is('div'):
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
Some of these solutions are going a bit overboard. All you need is tagName from regular old JavaScript. You don't really get any benefit from re-wrapping the whole thing in jQuery again, and especially running some of the more powerful functions in the library to check the tag name. If you want to test it on this page, here's an example.
$("body > *").each(function() {
if (this.tagName === "DIV") {
alert("Yeah, this is a div");
} else {
alert("Bummer, this isn't");
}
});
let myElement =document.getElementById("myElementId");
if(myElement.tagName =="DIV"){
alert("is a div");
}else{
alert("is not a div");
}
/*What ever you may need to know the type write it in capitalised letters "OPTIO" ,"PARAGRAPH", "SPAN" AND whatever */
I'm enhancing the answer of Andreq Frenkel, just wanted to add some and it became too lengthy so gone here...
Thinking about CustomElements extending the existing ones and still being able to check if an element is, say, input, makes me think that instanceof is the best solution for this problem.
One should be aware though, that instanceof uses referential equality, so HTMLDivElement of a parent window will not be the same as the one of its iframe (or shadow DOM's etc).
To handle that case, one should use checked element's own window's classes, something like:
element instanceof element.ownerDocument.defaultView.HTMLDivElement
Old question but since none of the answers mentions this, a modern alternative, without jquery, could be just using a CSS selector and Element.matches()
element.matches('div, ul, blockquote');
Try using tagName

Categories

Resources