Array check element ID with wildcard in if statement - javascript

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.

If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))

First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))

Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}

You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.

You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

Related

How can I use ".attr('disabled', false)" to btn[0]? [duplicate]

I'm new to jQuery, apologies if this is a silly question.
When I use it find an element using the id, I know theres always one match and in order to access it I would use the index [0]. Is there a better way of doing this?
For e.g.
var gridHeader = $("#grid_GridHeader")[0];
You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.
.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)
$("#grid_GridHeader:first") works as well.
You can use the first method:
$('li').first()
http://api.jquery.com/first/
btw I agree with Nick Craver -- use document.getElementById()...
http://api.jquery.com/eq/
$("#grid_GridHeader").eq(0)
You can use the first selector.
var header = $('.header:first')
With the assumption that there's only one element:
$("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()
...are all equivalent, returning the single underlying element.
From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
You can try like this:
yourArray.shift()

jQuery selector using regex (or something else)

I need to select an attribute in my code that match a string+number in the class name, using jQuery
What I need to do is to match something like that:
var myVar = 'item';
$('#id [class="'+myVar+'\d+"]');
My code contain other classes starting by "item" as well, so I can't use the selector class^="item"
I found out different things on Internet, but nothing that match perfectly my requirement.
I found the jQuery extension ":regex" but I'm not allowed to use it. http://james.padolsey.com/javascript/regex-selector-for-jquery/
I found the use of "filter" as a function but this is horrible for the performance
jQuery filter selector, is this right?
I tried to do something but it's not even working:
$('#id *').filter(function() {
return this.className.match("/"+myVar+"\d/");
});
Do you have some better suggestions?
Thanks.
No you can't use \d with CSS/jQuery selectors.
I suggest you split the number out into another attribute like data-number or something. This way you can target the class easily and efficiently and still have the number available.
<span class="my-class" data-number="1"></span>
<span class="my-class" data-number="6"></span>
<span class="my-class" data-number="10"></span>
jQuery example
$.each($('my-class'), function () {
$(this).attr('data-number');
});
As #Asad mentions they can also be selected using $('.my-class[data-number="1"]').
How about:
$('#id [class*=' + myVar + ']').filter(function() {
return this.className.match(new RegExp('(^|\\s)' + myVar + '\\d+(\\s|$)'));
});
Check jsfiddle demo here.
The selector picks every descendant element of #id with myVar in a class name. Finally it filters them, leaving only those who have myVar followed by one or more of digits as the name of one of its classes.
Note: You probably aready know that, but it is worth warning anyway: you must prevent myVar from having chars with special meaning to selectors (which would mess the [class*=' + myVar + ']' selector) and to regexes (such as the string '[a-z]', which would make the regex match a range instead of the literal '[a-z]' -- in this case, it should be escaped, as '\[a-z\]').

javascript regular expression

I want to match some links from a web content. I know I can use file_get_contents(url) to do this in php. How about in javascript?
For regular expression, like
contents
How can I use js regular expression to match this (match only once, do not greedy). I try to use this
/^\<a href=\"someurl\/something\" id=\"someid\"\>(+?)\<\/a\>$/
but it doesn't work.
Can someone help?
Thanks!
You should know that parsing HTML with regex is not the optimal way to solve this problem, and if you have access to a live DOM of the page, you should use DOM methods instead. As in, you should use
document.getElementById('someid').innerHTML // this will return 'contents'
instead of a regex.
I'd highly recommend using a library like jQuery to get the element, and then get the contents via a .text() call. It's much more simple and reliable than trying to parse HTML with regex.
DOM and jQuery suggestions are better but if you still want to use regex then try this:
/^<a href=".*?" id=".*?">(.*?)<\/a>$/
You might as well create the elements with jQuery
var elements = $(html);
var links = elements.find('a');
links.each(function(i, link){
//Do the regexp matching in here if you wish to search for specific urls only
});
In bigger documents, using the DOM is way quicker than regexping the whole thing as text.
Try this~
try {
boolean foundMatch = subjectString.matches("(?im)<a[^>]*href=(\"[^\"]*\"|'[^']*'|[^\\s>]*)[^>]*>.*?</a>");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Match double quotation marks,single quotes and empty.
contents
<a href='someurl/something' id='someid'>contents</a>
<a href=someurl/something id=someid>contents</a>

Determine if a string is a valid jQuery selector?

Does jQuery have a method to determine if an argument passed to function is a selector?
I am making a template for some jQuery plugins and I need to be able to check if the argument passed in is a jQuery selector. I want to allow for other data types and perform different methods based on what data type is passed. Detecting data types is easy, but selectors are just a string and can be constructed is many different ways.
My goal is to create plugins that are forgiving with what you pass in for the arguments and makes educated decisions about what to do with it. Take the jQuery UI plugins for example, in some plugins, lets say we pass a callback function in the argument place holder that is for a number for a speed, it still takes the callback and runs it and uses the default for speed. That's the kind of functionality I'm going for and selectors are a pretty unique case.
Has jQuery written a Regex for this? I couldn't find one in the code.
If not, I guess I'll just have to write a huge Regex for this?
To go straight to the point:
No, jQuery has no method to check if a selector is valid.
jQuery has lots of Regex' for this, that's why you cannot find one in the code.
You do not have to write a huge Regex for this, the answer is more simple as shown below.
I understand your problem because I experienced it, there are cases in which you're not in control of the selector to give to the jQuery function.
The problem not outlined enough is that if a selector is not valid jQuery throws an error (it is important because here is the answer).
Example using jQuery v1.9.1:
$('##somewhere');
It logs into the console the following line:
throw new Error( "Syntax error, unrecognized expression: " + msg );
which source is at row 4421 of the jQuery.js file (non-minified and uncompressed version).
So, instead of looking for an inner method of jQuery (which could surely simplify things but is not available), you can just listen the error thrown to establish if the selector is valid:
function isValidSelector(selector) {
if (typeof(selector) !== 'string') {
return false;
}
try {
var $element = $(selector);
} catch(error) {
return false;
}
return true;
}
You can also make it a jQuery plugin:
jQuery.extend({
isValidSelector: function(selector) {
if (typeof(selector) !== 'string') {
return false;
}
try {
var $element = $(selector);
} catch(error) {
return false;
}
return true;
}
});
to be used this way:
alert($.isValidSelector('#what?!?'));
Best regards.
EDIT:
added type validation: the selector must be a string.
Anyhow it is a partial solution, it does not return false for selectors defined as string objects var selector = new String('##wrong-selector#!');, which are not a primitive type.
Lots of strings can technically be a selector like $('blah') could select custom elements! There isn't any good way of knowing the intent of what to do with the argument passed to your function, so it's best to have a well defined structure like Gaby has commented.
Selector:
yourFunction({ selector: 'div' });
Or
yourFunction({ value: 'testing' });
Will take a different route in your code.
Without this technique the best you can do is just attempt for jQuery to find elements based on the selector, check with .length, if elements are found then assume the caller intended a jQuery selector. Another option could be just to document that a jQuery object must be passed i.e.:
yourFunction({ value: jQuery('div') });
Then for a different route you can do
if (value instanceof of jQuery) { .... }
There can not be a regex for this, since the selectors are extensible and anyone could add any number of personal selectors (with custom defined symbols etc) ...
Perhaps you should try passing your arguments as a single object with named parameters.
{ selector:'...',
otherargument:'somevalue',
afunction: function(){...}
}
The jQuery code for determining the selector is valid is about 108 lines long, so don't expect to determine if it's a valid selector or not in one RegEx statement.
Your best bet is probably to look at what jQuery determines to be a valid selector, and make a function that essentially checks the same way, but returns whether it's valid or not.
https://github.com/jquery/jquery/blob/master/src/core.js#L80-188
This does not answer your question, but i think it can be helpful. It checks not if an argument is a jQuery selector, however it tests whether the selector exists in the document.
$.fn.inDom = function() { return $(document).find(this).length; };
BTW: I dont use $(selector).length directly, since it will return 1 if the passed argument is an HTMLNode.
For better interpretation purposes:
$('foo').length // 0
$('.foo').length // 0
$('#foo').length // 0
$('<foo>').length // 1
$(document).find('foo').length // 0
$(document).find('.foo').length // 0
$(document).find('#foo').length // 0
$(document).find('<foo>').length // 0

Parsing XML with namespaces using jQuery $().find

I'm trying to get the contents of a XML document element, but the element has a colon in it's name.
This line works for every element but the ones with a colon in the name:
$(this).find("geo:lat").text();
I assume that the colon needs escaping. How do I fix this?
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
$(this).find("geo\\:lat").text();
That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.
Right now, jQuery can't deal with namespaces very well, see bug 155 for details.
Right now, as a workaround, you should be able to select these elements with just the local name:
$(this).find("lat").text();
If you have to distinguish between element types with the same local name, then you can use filter():
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("lat").filter(function() { return this.namespaceURI == NS; }).text();
Edit: my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and filter() if you need the namespacing too:
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("geo\\:lat").filter(function() { return this.namespaceURI == NS; }).text();
if you have a jquery selector problem with chrome or webkit not selecting it try
$(this).find('[nodeName=geo:lat]').text();
this way it works in all browsers

Categories

Resources