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
Related
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
}
}
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.
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
}
I ran into this very odd scenario.
This won't hide the H1:
if ($('#content h1').hasClass('active')) {
$(this).hide();
}
Only this will:
if ($('#content h1').hasClass('active')) {
$('#content h1').hide();
}
Why can't I use the (this)? Is something wrong with the script?
That is the correct behaviour. In the context of your if statement this does not hold a reference to your h1 element but to the document element (or function if you are inside of a function).
You could do:
$('#content h1').foreach(function() {
if (!$(this).hasClass('active')) {
$(this).hide();
}
});
In this case, as Jan explained, this will be in the context you expect it to be (the heading element).
What you want is probably
var h1 = $('#content h1')
if (h1).hasClass('active')) {
h1.hide();
}
your "this" will, as stated above, not reference your object.
The statement $('#content h1').hasClass('active') returns a Boolean value (true or false), as opposed to a jQuery object, which is what you're trying to use $(this) for. See the usage of hasClass here.
If you're trying to perform an action on all elements that match a certain selector, give this selector a try instead:
$("#content h1.active").hide();
This finds all elements with an id attribute of "content" that contain an h1 element with a class attribute of "active," and hides them all.
I've got a javascript function that gets called on change event of a select form element. So, the "this" variable in js refers to the select element.
This select element is in a td tag, in a tr tag. The tr tag has a classname of "FilterDetailsRow".
Now, I've tested, and if I use this syntax:
var filterRow = $(this).parent().parent();
it gets me what I want. However, is there a better way to tell jQuery, "starting with "this" can you please go up my tree of parents until you find one with a classname of "FilterDetailsRow"?
Here's what I came up with, but I want to make sure I"m not reinventing the wheel.
function GetFilterDetailsRowOfObject(o) {
if (o) {
if (o.parent()[0].className.indexOf("FilterDetailsRow") != -1)
return o;
else
return GetFilterDetailsRowOfObject(o.parent());
} else {
return null;
}
}
Thanks for any advice.
You can use closest to find the first matching ancestor:
var filterRow = $(this).closest('.FilterDetailsRow');
In jQuery 1.4 you can use parentsUntil. For you it would be something like
$(this).parentsUntil('.FilterDetailsRow');