jQuery if Element has an ID? - javascript

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.

Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified

You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.

You can do
document.getElementById(id) or
$(id).length > 0

You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?

Number of .parent a elements that have an id attribute:
$('.parent a[id]').length

Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}

I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}

Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo

Simply use:
$(".parent a[id]");

You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}

You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

Related

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

How can I check whether element exists based on the classname?

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.
Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.
check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}
You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/
Try this:
if($('.classname').length > 0)
{
alert('exist');
}
You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.
You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}
try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Recursively remove empty nodes from html

I'd like to remove empty elements from some html string. I know I could run something like:
$('p').each(function(index, item) {
if($.trim($(item).text()) === "") {
$(item).remove();
}
});
The problem is that I want to remove all empty nodes - not only p. Also I want the script to consider p node in <p><span></span></p> as empty because it contains only empty elements. Do you have some simple implementation of something like that?
[EDIT]
I forgot to add: I can use jQuery but the html I want to traverse and edit is in a string - not the actual document. So how can I do this operation? I tried using var html = $.parseHTML('<p><span></span></p>') but after each loop I still get the same string...
Recently I was looking for a solution to the same problem. A recursive function was the answer.
function removeEmptyTagsRecursively($el) {
if ($el.children().length) {
$el.children().each(function(i, val) {
removeEmptyTagsRecursively($(val));
});
$el.children(':empty').remove();
}
}
Fiddle here: https://jsfiddle.net/635utakr/9/
Here's a tweek of Paul's function for vanilla JS (requires Element.matches() polyfill):
function removeEmpty(parent) {
// for each child
[].forEach.call(parent.children, function(child) {
// repeat operation
removeEmpty(child);
// remove if it matches selector
if (child.matches(':empty')) {
parent.removeChild(child);
}
});
}
Try something like
do {
empty = $("*:empty");
count = empty.length;
empty.remove();
}
while ( count > 0 );
It's iterative rather than recursive, but should do the trick
Actually Your code is working Fine. See this fiddle.
It's showing only, which having content inside. Then What you Want?
HTML
<p>hi 1</p>
<p></p>
<p><span>hi 2</span></p>
<p><span></span></p>
Script
$('p').each(function(index, item) {
if($.trim($(item).text()) === "") {
$(item).remove();
}
});
You can achieve this using below code:-
function removeEmptyTag(root) {
var $root = $(root);
$root.contents().each(function () {
if (this.nodeType === 1) {
removeEmptyTag(this);
}
});
if (!$root.is("area,base,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr") && !$root.html().trim().length) {
$root.remove();
}
}
removeEmptyTag("#divIdHere");
Fiddle

jQuery check if target is link

I have a global function to capture clicks.
$(document).click(function(e){
//do something
if(clickedOnLink)
//do something
});
I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.
http://jsfiddle.net/Af37v/
You can try to see if the element you clicked on either is or is a child of an <a> tag.
$(document).click(function(e){
if($(e.target).closest('a').length){
alert('You clicked a link');
}
else{
alert('You did not click a link');
}
});
I believe using is will actually have better performance than the answers suggesting closest:
$(e.target).is('a, a *');
This checks if the element itself is an a or if it is contained with an a.
This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
If the exact target is link, then you can use .is()
Example:
$(".element").on("click", function(e){
if($(e.target).is("a")){
//do your stuff
}
});
EDIT:
If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length
Example:
$(".element").on("click", function(e){
if($(e.target).closest("a").length){
//do your stuff
}
});
With jquery just get the tagName attribute
$("a").prop("tagName");
Updated:
You could check if the target is an a or if a parent is an a.
$(function () {
$(document).on('click', function (e) {
$target = $(e.target);
if ($target.closest('a').length > 0) {
alert('i am an a');
}
});
});
http://jsfiddle.net/8jeGV/4/
You can test if there's a <div> under <a> by testing if the .children() <div> has anything inside it. If nothing is inside, or there is no <div>, the if statement will return false.
I suggest this code:
$(document).click(function(e){
var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false),
//run code
if ( willRedirect === false ){
e.preventDefault();
//the link will not redirect
if ( $(this).children('div').html() ){
//there is a <div> inside <a> containing something
}
else {
//there is no <div> inside <a>
}
}
else {
//the link is not pointing to your site
}
});

Check if Attribute('id') Exists in jQuery

How can I check if an attribute Id exists in jQuery?
I searched around and found that this should work:
if ($(this).attr('id').attr('id'))
{
}
I still get this error: TypeError: Object gauge1 has no method 'attr'
This itself will work:
if($(this).attr("id"))
Check existing jsfiddle on the issue: http://jsfiddle.net/rwaldron/wVqvr/4/
Just try it the old way
if (this.id) {
//do something
}
You can use the is method and the Has Attribute Selector:
if ($(this).is('[id]')) {
}
if ($(this).attr('id')){
alert(id);
}
you could also just use the plain js object
if( this.id !== undefined && this.id.length > 0 ){
//todo: use id
}
HTML:
<div class="hey"></div>
<div class="you" id="woah"></div>
<div id="results"></div>​
jQuery:
var id = $('div.hey').attr('id');
if (id) {
// Have an id.
} else {
// Don't have an id.
}
A fiddle: http://jsfiddle.net/NEVYT/

Categories

Resources