Select li classname if it exists - javascript

Each time a button is clicked i'm entering a function where I check if a listitem with specific classname exists. If it exists, then it has to be removed.
if($("ul#" + this.listClass + " li[class='errorlist']"))
{
console.log("error");
}
Now, it enters the function each time I click, even if it doesn't exist.
Thanks in advance.

If you want to check for class existing
if($('myElement').hasClass('myClassToCheckFor')){
//do stuff to my element here
}
if you want to check for element existing
if($('myElement.withMyClass').length > 0) {
//do stuff to my element here
}
So what you want to do is this (this is however not optimized for caching of jquery object but it demonstrates what you need to do).
$('button.myButton').click(function(){
if($('ul li').hasClass('monkey')){
$('ul li.monkey').remove();
} else {
alert("not found!");
}
});
See this fiddle

This could help
var test = document.getElementById('test') //returns a HTML DOM Object
var test = $('#test') //returns a jQuery Object
var test = $('#test')[0] //returns a HTML DOM Object
So you can use if($('#test')[0]) to check if the element exists in the DOM.
Example also to check if the element has a class
if($('#test')[0] && $('#test').hasClass("test")) {
$('#test').removeClass("test");
}

Related

Using .after but only if the value does not exist

I am running this code to insert a HTML line after the id #wp_menu:
$(document).on('closing', '.remodal', function (e) {
$('.menu_name').each(function() {
$('#wp_menu').after('<div class="tag">' + $(this).val() + '</div>');
});
});
The problem is, every time I run this loop, I'll get duplicated values and this is not what I want. How can I check if the code was inserted before?
This is a simple example that may explain my problem: https://jsfiddle.net/vLqonqpk/
So when you click on "add" multiple times, it will add the same values over and over again.
You could do something like this:
arr = [];
$('button').click(function() {
$('ul input').each(function() {
if ($.inArray($(this).val(), arr) == -1) {
$('#wp_menu').after('<div class="tag">' + $(this).val() + '</div>');
arr.push($(this).val());
}
});
console.log(arr);
});
DEMO: https://jsfiddle.net/vLqonqpk/1/
So, create array of values, check if current val(s) from inputs are duplicated, and place just unique values. Of course, you can add additional checks for empty string, and give user some alerts/warnings (create else block for that purpose), if needed, etc, etc...
But this is basic idea which should work.
Simply isolate the jQuery selector and check its existence.
$(document).on('closing', '.remodal', function (e) {
$('.menu_name').each(function() {
var $wp_menu = $('#wp_menu');
var $tag = $wp_menu.next('.tag'); // .siblings() also works
// Now you check if it exists, and create it if not
if (!$tag.length)
$tag = $('<div class="tag">').insertAfter($wp_menu);
// Simply update the content, element will always exist
$tag.text($(this).val()); // .html() also works
});
});
I'm sure there's several ways to do it, this is just one of them.
I now realize your problem is not duplicating tags, but values. Basically you want a HashSet. Please accept sinisake's answer instead

JS event listener for a type of element?

Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element
the easiest answer would be using addEventListener() if you want a specific html tag just like what i wanted in my question then you'll find the answer there ill paraphrase it here too
add this
<script>
document.addEventListener("click", function(e){
//your desired nodeName like : DIV , SPAN , LI etc
if(e.target && e.target.nodeName== 'DIV')
//add a function below to trigger
{alert('bingo')}
});
</script>
to the end of your document
by the way don't forget to use uppercase nodeNames or just put a toLowerCase() before it. cheers :)
Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a <span> inside a <p>, clicking the span won't trigger the click in the paragraph.
document.addEventListener("click", function (eventArgs) {
var target = eventArgs.target;
var elementToLookFor = "p";
while (target !== null) {
if (target.tagName.toLowerCase() === elementToLookFor) {
// Do magic stuff with the paragraph
console.log(target);
}
target = target.parentElement;
}
});
This technique is called "event delegation."
Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.
<p>
Hey,
<p>there!</p>
</p>
Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.
I assume that you are looking for code along these lines:
var paras = document.getElementsByTagName("p");
// Loop through elements.
for(var i = 0; i < paras.length; i++) {
// Add listener.
paras[i].addEventListener("click",
function() {
// Execute function.
}, false);
}
I'd just select all the elements on the page and add eventListeners on them like so:
function addListeners(elementType, eventType, callback) {
Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
el.addEventListener(eventType, callback, false);
});
}
Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.
Here's an example: https://jsfiddle.net/a7en4d4s/
Look at this JSFiddle, and see if it works for you
<span>Click Yes</span><br/><br/>
<span>Click No</span><br/><br/>
<a>Clicked: <b id="result"></b></a>
<script>
$("span").click(function(){
var a = $(this).html();
$("#result").html(a);
});
</script>

Is there a way to know if the element is inside a table or a list?

I'm making a generic delete function that will delete a record and then delete the <tr> if the element is inside a <table>, or the <li> if it's inside a <ul>
The element can be in a list inside a table, so I need to know what parent element is closest.
Is there a way to find out this using jQuery?
If I understand you correctly, you want something like this:
if ($(this).closest('li').length) {
$(this).closest('li').remove();
} else { // must be in a table
$(this).closest('tr').remove();
};
http://api.jquery.com/closest
In the unlikely event your element is in a table inside a li, you need to be more creative:
if ($(this).closest('li').length) {
if ( $(this).closest('li').is($(this).closest('tr').closest('li')) ) {
// then we're in a table inside an li
$(this).closest('tr').remove();
} else {
$(this).closest('li').remove();
};
} else { // must be in a table
$(this).closest('tr').remove();
};
http://api.jquery.com/is
You can use closest() jQuery function.
function elementInTable(element) {
if (element.closest("table").length) return true;
return false;
}
Another solution is to search for each table and see if your element is in the table:
function elementInTable(element) {
element = $(element);
$("table").each(function () {
var currentTable = $(this);
if (currentTable.find(element).length) {
return true;
}
});
return false;
}
I guess it's not the best, but can be a solution.
if($(/*query*/).parent().is('table')){}
or if it's not a direct child
if($(target).parents('table').length > 0) {
//do something...
}
You can use the jquery.parents() function to retrieve the closest parent of a given selection:
$(myElemToDelete).parents('tr').remove();
There are several good answers on how to accomplish what you want, but I wonder about the initial premise... could you pass the id of the container to the function?
<li id="li_0">Some content <span class="delete" onclick="deleteRow('li_0')">Delete</span></li>
This would give your function flexibility to work in any structure. But, I don't know if that would really work for what you're wanting.
First,check whether the parent exist or not.
If it does,then check whether its input/tr or whatever element you want to delete and then remove.
if ($(event.target).parent('.selector').size() > 0)
{
$("#elementId").is("input")//or tr or whatever!!!
{
//your removal code
}
}

jquery - is it possible to see if a cached element is hidden or not

I've cached a DOM element in jquery and wondered how i can see if it's hidden or not.
I have no problem doing by a normal selector. With a normal selector i'd do something like this if statement:
if('.someClass:hidden') {
console.log('hidden')
}
else {
console.log('not hidden');
}
But instead of .someClass i had the element cached. Like this, details being the cached element:
$this = $(this);
details = $this.find(".details");
Many Thanks
B
for a cached element you can use is()
var $cachedElement = $('#cachedElement');
if($cachedElement.is(':hidden')){
console.log('hidden')
}else {
console.log('not hidden');
}

How to call a function with jQuery blur UNLESS clicking on a link?

I have a small jQuery script:
$('.field').blur(function() {
$(this).next().children().hide();
});
The children that is hidden contains some links. This makes it impossible to click the links (because they get hidden). What is an appropriate solution to this?
This is as close as I have got:
$('.field').blur(function() {
$('*').not('.adress').click(function(e) {
foo = $(this).data('events').click;
if(foo.length <= 1) {
// $(this).next('.spacer').children().removeClass("visible");
}
$(this).unbind(e);
});
});
The uncommented line is suppose to refer to the field that is blurred, but it doesn't seem to work. Any suggestions?
You can give it a slight delay, like this:
$('.field').blur(function() {
var kids = $(this).next().children();
setTimeout(function() { kids.hide(); }, 10);
});
This gives you time to click before those child links go away.
This is how I ended up doing it:
var curFocus;
$(document).delegate('*','mousedown', function(){
if ((this != curFocus) && // don't bother if this was the previous active element
($(curFocus).is('.field')) && // if it was a .field that was blurred
!($(this).is('.adress'))
) {
$('.' + $(curFocus).attr("id")).removeClass("visible"); // take action based on the blurred element
}
curFocus = this; // log the newly focussed element for the next event
});
I believe you can use .not('a') in this situation:
$('.field').not('a').blur(function() {
$(this).next().children().hide();
});
This isn't tested, so I am not sure if this will work or not.

Categories