jQuery contains doesn't work on Chrome - javascript

I have one problem with jquery contains. It work perfect on firefox.
This is my code.
$("input[data-height='cm']").blur(function(){
var text = $(this).val();
if($(this).val().length > 0) {
if(!$(this).val().contains("cm")) {
$(this).val(text + " cm");
}
}
});
on chrome it give error
Uncaught TypeError: $(...).val(...).contains is not a function
How can I fix it please help.
Thank you.

Use indexOf instead of contains
if($(this).val().indexOf("cm") == -1) {
$(this).val(text + " cm");
}

.contains() checks to see if a DOM element is a descendant of another DOM element hence you should use it with jquery Objects:
Here you can use indexOf() function to check the contents of value attribute.
if($(this).val().indexOf("cm")>=0) {
}
You can refer .contains() for more info.

You could use test:
if(!/cm/.test($(this).val())) {
$(this).val(text + " cm");
}

There is no such method as contains in Chrome. Instead, you should better use indexOf:
// Instead of...
if ($(this).val().contains('cm')) { /* val() contains 'cm' */ }
// ...do this:
if ($(this).val().indexOf != -1) { /* val() contains 'cm' */ }
Please note that indexOf returns -1 if occurence is not found in string and >= 0 if occurence is found.

Related

Check if string is starting with prefix

I would like to check with javascript if array items starts with the word "prefix".
So far I've done something like this:
let array = ["prefix-word1", "prefix-word2"];
array.forEach(function(element) {
if (element.lastIndexOf('prefix', 0) == 0) {
console.log('prefix');
}
}
For some reason I keep get an error that prefix is not defined. Please help.
This one works (check the comments on the code):
let array = ["prefix-word1", "prefix-word2" , "does not start with prefix"];
array.forEach(function(element) {
// Check if the first word is prefix
if (element.indexOf('prefix') == 0) {
console.log('prefix');
console.log(element);
}
});
console.log("Second approach which is not suggested");
array.forEach(function(element) {
// not the correct approach as suggested by #Barmar though it works
if (element.lastIndexOf('prefix',0) == 0) {
console.log('prefix');
console.log(element);
}
});
Try using double quotation marks instead of single like this "prefix" in functions.

Jquery.append() in certain position of class selector

I have this jQuery code:
var $collapsibleProducts = $('.collapsible-body');
if ($collapsibleProducts.length != 0) {
$.each($('.collapsible-body'), function (i) {
if ($('.collapsible-body')[i].children.length === 0) {
$('.collapsible-body')[i].append("<span class='something'>something</span>")
}
});
}
But I only getting inside my div.collapsible-body this string "<span class='something'>something</span>" instead of html <span> tag with 'something' string.
Like this (image)
Is there something I doing wrong? or is there another way to do it?
No need to check for the length (jQuery's easy like that), and you're using the wrong kind of each. You're using the general iterator whereas jQuery has a special iterator for jQuery objects.
var $collapsibleProducts = $('.collapsible-body');
$collapsibleProducts.each(function(i, el) {
if ($(el).children().length === 0) {
$(el).append("<span class='something'>something</span>");
}
});

Jquery search througha class check if it has a certain id

hey I want to search through a class and check if that class contains a certain id. Do I have to use .each? if i do i dont know how to exactly use it, could someone show me how to use it in this context,
any help is appreciated
if(id == $('.people').attr('id'))
{
alert("person exists");
}
since ids should not be used more than once, you simply can do:
if($('#' + id + '.people').length >= 1)
alert('person exists');
You can search for an ID with
$('#my-id')
In your case,
$('#' + id)
You can check if the result is empty by testing for length:
if($('#'+id).length == 0)
To verify that it is a .person element that has the given ID, you could test
if($('.person#'+id).length > 0) {
alert('person exists');
}
Since an id can only be used once you can instead search for the element with that id and check if it has the class. That will be much faster:
$('#the-id').hasClass('the-class');
One solution would be to use a simple selector, and check if that element exists.
if ($('.people#'+id).length()) { //Checking length() checks if element exists
alert("person exists");
}

jQuery: Check if div with certain class name exists

Using jQuery I'm programmatically generating a bunch of div's like this:
<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>
Somewhere else in my code I need to detect if these DIVs exist. The class name for the divs is the same but the ID changes for each div. Any idea how to detect them using jQuery?
You can simplify this by checking the first object that is returned from JQuery like so:
if ($(".mydivclass")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
In this case if there is a truthy value at the first ([0]) index, then assume class exists.
Edit 04/10/2013: I've created a jsperf test case here.
You can use size(), but jQuery recommends you use length to avoid the overhead of another function call:
$('div.mydivclass').length
So:
// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {
http://api.jquery.com/size/
http://api.jquery.com/length/
UPDATE
The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:
http://jsperf.com/check-if-div-exists/3
My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.
Without jQuery:
Native JavaScript is always going to be faster. In this case: (example)
if (document.querySelector('.mydivclass') !== null) {
// .. it exists
}
If you want to check to see if a parent element contains another element with a specific class, you could use either of the following. (example)
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it exists as a child
}
Alternatively, you can use the .contains() method on the parent element. (example)
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it exists as a child
}
..and finally, if you want to check to see if a given element merely contains a certain class, use:
if (el.classList.contains(className)) {
// .. el contains the class
}
$('div').hasClass('mydivclass')// Returns true if the class exist.
Here is a solution without using Jquery
var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
// Class exists
}
reference link
It's quite simple...
if ($('.mydivclass').length > 0) {
//do something
}
To test for div elements explicitly:
if( $('div.mydivclass').length ){...}
Here are some ways:
1. if($("div").hasClass("mydivclass")){
//Your code
//It returns true if any div has 'mydivclass' name. It is a based on the class name
}
2. if($("#myid1").hasClass("mydivclass")){
//Your code
// It returns true if specific div(myid1) has this class "mydivclass" name.
// It is a based on the specific div id's.
}
3. if($("div[class='mydivclass']").length > 0){
//Your code
// It returns all the divs whose class name is "mydivclass"
// and it's length would be greater than one.
}
We can use any one of the abobe defined ways based on the requirement.
The simple code is given below :
if ($('.mydivclass').length > 0) {
//Things to do if class exist
}
To hide the div with particuler id :
if ($('#'+given_id+'.mydivclass').length > 0) {
//Things to do if class exist
}
Best way is to check the length of the class as shown below:
if ($('.myDivClass').length) {
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
Use this to search whole page
if($('*').hasClass('mydivclass')){
// Do Stuff
}
Here is very sample solution for check class (hasClass) in Javascript:
const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
// do something if 'hasClass' is exist.
}
In Jquery you can use like this.
if ($(".className")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
With JavaScript
if (document.getElementsByClassName("className").length > 0) {
// Do something if class exists
}else{
// Do something if class does not exist......
}
check if the div exists with a certain class
if ($(".mydivclass").length > 0) //it exists
{
}
if($(".myClass")[0] != undefined){
// it exists
}else{
// does not exist
}
The best way in Javascript:
if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
if ($(".mydivclass").size()){
// code here
}
The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}

Get class list for element with jQuery

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
ex.
<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.
Then you can iterate and find the one you want.
var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
jQuery does not really help you here...
var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item === 'someClass') {
//do something
}
});
Why has no one simply listed.
$(element).attr("class").split(/\s+/);
EDIT: Split on /\s+/ instead of ' ' to fix #MarkAmery's objection. (Thanks #YashaOlatoto.)
On supporting browsers, you can use DOM elements' classList property.
$(element)[0].classList
It is an array-like object listing all of the classes the element has.
If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.
Here is a jQuery plugin which will return an array of all the classes the matched element(s) have
;!(function ($) {
$.fn.classes = function (callback) {
var classes = [];
$.each(this, function (i, v) {
var splitClassName = v.className.split(/\s+/);
for (var j = 0; j < splitClassName.length; j++) {
var className = splitClassName[j];
if (-1 === classes.indexOf(className)) {
classes.push(className);
}
}
});
if ('function' === typeof callback) {
for (var i in classes) {
callback(classes[i]);
}
}
return classes;
};
})(jQuery);
Use it like
$('div').classes();
In your case returns
["Lorem", "ipsum", "dolor_spec", "sit", "amet"]
You can also pass a function to the method to be called on each class
$('div').classes(
function(c) {
// do something with each class
}
);
Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/
Minified Javascript
;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);
You should try this one:
$("selector").prop("classList")
It returns a list of all current classes of the element.
var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){
//do something
});
$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})
Update:
As #Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).
const classes = element.className.split(' ').filter(Boolean);
or more modern
const classes = element.classList;
Old:
With all the given answers, you should never forget to user .trim() (or $.trim())
Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2 class3'..
This would turn into ['class1', 'class2','','','', 'class3']..
When you use trim, all multiple spaces get removed..
Might this can help you too. I have used this function to get classes of childern element..
function getClickClicked(){
var clickedElement=null;
var classes = null;<--- this is array
ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
clickedElement = $(e.target);
classes = clickedElement.attr("class").split(" ");
for(var i = 0; i<classes.length;i++){
console.log(classes[i]);
}
e.preventDefault();
});
}
In your case you want doler_ipsum class u can do like this now calsses[2];.
Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.
In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:
$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});
function toggleHelp(obj, mode){
var classList = obj.attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item.indexOf("_toggle") > 0) {
var targetClass = "." + item.replace("_toggle", "");
if(mode===false){$(targetClass).removeClass("off");}
else{$(targetClass).addClass("off");}
}
});
}
Try This. This will get you the names of all the classes from all the elements of document.
$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
if ($(this).hasClass('') === false) {
var class_name = $(this).attr('class');
if (class_name.match(/\s/g)){
var newClasses= class_name.split(' ');
for (var i = 0; i <= newClasses.length - 1; i++) {
if (currentHtml.indexOf(newClasses[i]) <0) {
currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
}
}
}
else
{
if (currentHtml.indexOf(class_name) <0) {
currentHtml += "."+class_name+"<br>{<br><br>}<br>"
}
}
}
else
{
console.log("none");
}
});
$("#Test").html(currentHtml);
});
Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/
For getting the list of classes applied to element we can use
$('#elementID').prop('classList')
For adding or removing any classes we can follow as below.
$('#elementID').prop('classList').add('yourClassName')
$('#elementID').prop('classList').remove('yourClassName')
And for simply checking if the class is present or not we can use hasClass
I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:
$('<img>').hasClass("nameOfMyClass");
but I got a nice "this function is not available for this element".
Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.
$('img').className // it contains "class1 class2 class3"
Once you get this, just split the string as usual.
In my case this worked:
var listOfClassesOfMyElement= $('img').className.split(" ");
I am assuming this would work with other kinds of elements (besides img).
Hope it helps.
javascript provides a classList attribute for a node element in dom. Simply using
element.classList
will return a object of form
DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}
The object has functions like contains, add, remove which you can use
A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');
(function($) {
$.extend({
hasClass: new function(className) {
var classAttr = $J(this).attr('class');
if (classAttr != null && classAttr != undefined) {
var classList = classAttr.split(/\s+/);
for(var ix = 0, len = classList.length;ix < len;ix++) {
if (className === classList[ix]) {
return true;
}
}
}
return false;
}
}); })(jQuery);
The question is what Jquery is designed to do.
$('.dolor_spec').each(function(){ //do stuff
And why has no one given .find() as an answer?
$('div').find('.dolor_spec').each(function(){
..
});
There is also classList for non-IE browsers:
if element.classList.contains("dolor_spec") { //do stuff

Categories

Resources