jquery find not getting the invalid elements - javascript

I have this div inside my page;
<div class="workspace" id="workspace">
<div data-ng-repeat="node in controller.Nodes" on-last-repeat=on-last-repeat>
</div>
</div>
On my typescript code, I have this to check if there are required fields that are not set.
if ($('#workspace').find('.ng-invalid').length != 0)
This is not working. The length is always 0. I also tried the following below but no luck:
if ($('#workspace').find('.has-error.form-control').length != 0)
if ($('#workspace').find('.invalid').length != 0)
Any ideas?

child element do not have class attribute. You can rather use has attribute selector:
if ($('#workspace').find('[data-ng-repeat]').length != 0)

Is it possible that it is because you run the JQuery part before the document is completely ready?
I have an example like this:
if ($('#workspace .ng-invalid').length != 0) {
console.log('found in FIRST');
}
// on document.ready
$(function() {
if ($('#workspace .ng-invalid').length != 0) {
console.log('found in SECOND');
}
});
and only the second triggers.
To iterate over all invalid elements with JQuery use each(index, object):
$(function() {
$('#workspace .ng-invalid').each( function (index, object) {
console.log(object);
});
});

Related

What's the proper way to check if an element has an ID or not with jQuery?

I thought I could check if an element has an ID with has() like this:
if ($button.has('#Menu-Icon')[0] !== undefined) {
//do stuff
}
but I learned that instead, it checks if there's a descendant which matches the ID. So I don't think this is the right jQuery method to use, but nevertheless it's the only thing that seems to show up when I search the subject on Google.
Which jQuery method is the right one for checking if a given element has a certain ID or not?
Check the id using the attr() function like this:
$('button').on('click', function() {
if ($(this).attr('id') == 'TheID') {
alert('The button you pressed has the id: "TheID"!');
} else {
alert('You pressed a button with another id..');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="TheID">TheID</button>
<button id="anotherID">anotherID</button>
You can check the id property like of the underlying element like
if ($button[0].id == 'Menu-Icon') {
//do stuff
}
or jQuery way to use .is()
if ($button.is('#Menu-Icon')) {
//do stuff
}
The has() method is used to filter a set of elements by checking whether those contains elements matching the passed selector, also it returns a jQuery object so checking for undefined will never be true
Try something like below which should work:
<div id=""></div>
$(document).ready(function(){
if($('div').attr('id') != ''){
alert("have id");
}else{
alert("do not have id")
}
});

How to check if value of input is empty after browser refresh?

I want to hide all inputs with class "chang" that contain any value after browser refresh, but entered by the user before refreshing. I tried few things, and nothing works. It's my HTML code:
<input class="chang" id="test1" /> <input class="chang" id="test2" />
And script:
$(document).ready(function() {
if( $(".chang").val().length != 0 ) {
$(this).hide();
}
});
I tried to make it works in Firefox (if it's matter). What am I doing wrong in this case?
$(document).ready(function() {
$('.chang').each(function(index){
if($(this).val().length != 0){
$(this).hide();
}
});
});
Use each() to iterate multiple elements with same class.
Try this:
$(".chang").each(function(){
if($(this).val().length != 0) {
$(this).hide();
}
});
It iterates over each of the .chang elements allowing you to use the $(this) correctly
DEMO
You have to check if the value of the input is empty like this:
if( $(".chang").val() == "" ) {
$(this).hide();
}
fiddle

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 if Element has an ID?

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

$(.class) only executes for the first tag of that class name

I am trying to make a javascript function that goes through the web page and looks for all of the tags of class name "option" and hides the ones that match the text in each of the if statements shown below.
In the example below, I tried using jquery to get the classes, but it only gets the first class with that name, not all of the classes of that name.
I have also tried using var element = document.getElementsByClassName('option'); to see if that would work but when I iterated through the list of elements and changed their display to none, the changes didn't show up.
What is a better way to iterate through a list of classes and update the css of only some of the elements?
Any help is appreciated. Thanks.
$(document).ready(function(){
if($('.option').html() == "C. "){
$('.option').css('display','none');
}
if($('.option').html() == "D. "){
$('.option').css('display','none');
}
if($('.option').html() == "E. "){
$('.option').css('display','none');
}
if($('.option').html() == "F. "){
$('.option').css('display','none');
}
});
You're not getting only one element, you just simply only manipulating the "first" element in the jQuery Object that is returned by the $('.option') call. What you need to is jQuery's .each() function in order to iterate through ALL of the elements returned by the jQuery call. Also, the long if statement can be shortened, but I assume you knew that and have other purposes. Anyway, once .each is called, you can use the callback function to manipulate EACH element as it is passed through. This is much like a for loop. The parameter i in the following example represents the index value of the element as the object is iterated through. It is 0 based, in other words, the 3rd option element to pass through would set the param i to 2
Try this && Good Luck:
$(function() {
$(".option").each(function(i) {
var txt = $(this).text();
if (txt == "C." || txt == "D." || txt == "E." || txt == "F.")
$(this).hide();
});
})
Alternate links to investigate
.html()
Use this method to get or set the innerHtml of an element
.val()
Use this method to get or set the value of an element
Primarily HTML tags select, input, && textarea
If I understood what you want, this should work:
$(document).ready(function(){
$('.option').each( function(i,e) {
var current = $(e).html();
if (current == "C" || current == "D" ||
current == "E" || current == "F") {
$(e).hide();
}
});
Use the .each function
$('.option').each(function(index) {
if($(this).html == "E")
$(this).hide();
});
$('.option').html() will only get the innerHTML of the 1st element. If you want to look at all of them, you need to use $.each.
$('.option').each(function(){
if($.inArray($(this).html(), ['C', 'D', 'E', 'F']) !== -1){
$(this).hide();
}
});
I see You are using jQuery.
When you wrapp some class with jQuery function like this $('.option') you will get an element set, meaning it will containg all of those elements wrapped in special jQuery classes that offer you a lot of functionality
Best way to iterate trough element set is by using jquery .each() function, http://api.jquery.com/jQuery.each/
it will apply callback function to every element.
Something like this:
$(document).ready(function(){
$('.option').each(function() {
//Here you can access coresponding element to each iteration with this kyeword
// you can wrap it again like this $(this) and get all of jQuery functionality on that object again
$(this).hide();
});
}
Try this:
$(document).ready(function(){
$('.option:contains("C.")').hide();
$('.option:contains("D.")').hide();
$('.option:contains("E.")').hide();
$('.option:contains("F.")').hide();
});
The JQuery selector '.option:contains("C.")' finds all tags of the option class that contain the text "C.", and the .hide() function hides each element in that collection.
http://jsfiddle.net/b3hVw/
Or alternatively, in a single statement:
$(document).ready(function(){
$('.option').filter(function() {
var html = $(this).html();
return html === "C." || html === "D." || html === "E." || html === "F.";
}).hide();
});
$('.option') finds all the elements with the option class. The .filter(function() { ... }) call filters that list to just the ones for which the filter function returns true, and then the call to .hide() hides those elements.
http://jsfiddle.net/H7Lu8/

Categories

Resources