Jquery search througha class check if it has a certain id - javascript

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

Related

Finding if a string already exists inside an array of strings -javascript

I have an array called blog.likes and i want to check to see if the id of the current logged in user(req.user._id) already exists inside the array of likes. If it does then delete the id from the array if it doesn't then add the user id inside the array. With the code i have now if i press the like button once it likes the post if i press it again it removes the like but if a post has a like and i log in with a different user and press the like button many times it starts to delete all the likes not only the likes that are made by one user.
if (blog.likes.indexOf(req.user._id) > -1 ){
blog.likes.shift(req.user._id);
blog.save();
} else {
blog.likes.push(req.user);
blog.save();
}
The shift function will only remove the first element from the array, paying no heed to the logged in user id. Use splice function to achieve the desired result.
Change your code to this:
let userIndex = blog.likes.indexOf(req.user._id);
if (userIndex > -1) {
blog.likes.splice(userIndex, 1);
} else {
blog.likes.push(req.user);
}
blog.save();
As I mentioned in the comments .shift() is not the correct method to use. Give this a try:
var f = blog.likes.indexOf(req.user._id);
if (f > -1 ) {
blog.likes.splice(f, 1);
} else {
blog.likes.push(req.user);
}
blog.save();

jQuery contains doesn't work on Chrome

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.

js Search String and get matched elements

I want to ask what is the best way to search string and get matched element?
//I want to get similar or matched element and the index of it.
//Search key ward
var key = 'Pap';
<ul>
<li>Papa</li>
<li>Mama</li>
</ul>
My Idea now is use $.each and match its text of each, but I believe that should be a wrong way. However, I couldn't find any references from net about this question.
Thank you very much.
Use :contains selector
$('*:contains("'+key+'"):last')
To find exact match will the whole text in element use this
$.fn.exactMatch = function (key) {
var p = $(this).find(':contains("' + key + '"):last');
if (p.text() == key) {
p.css('background', 'yellow');
} else {
//Not exact match function if wanted
}
}
To use this function do this
$(el).exactMatch(key);

jQuery creating element names

Hey weird question but I am writing some code and I want to clean it up... The code goes as follows...
function (item){
if(item == "1")
$('div').show();
if(item == "2"
$('div1').show();
}
I tried something like
function (item)
var $div = div+item;
$($div).show()
Thanks
function (item){
$("#div" + (item > 1 ? (item - 1) : "")).show();
}
Assuming you mean #div + n, since div1 is not a valid selector. However, the logic should be the same no matter what the prefix of your actual selector is.
Example: http://jsfiddle.net/XXSTy/
For information on the conditional operator, check this MDN article.
There are several errors in your code.
2nd if statement is missing )
you are trying to find <div1> element
There is no div1 element. If you want to refer element IDs you must use "#" so it becomes $('#idofthediv').
Your code is a bit confusing and it is not clear if you want to search for IDs, element names or it is mixed.
If you want to search for IDs div and div1 then just rename 1st id to div0 and the code will get cleaner (or better div1 and div2):
function (item) {
$("#div" + (item - 1)).show();
}

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

Categories

Resources