Search the Community
Showing results for tags 'sizzle'.
-
Split multiple selectors for use with jQuery
guinness posted a topic in Developer General Discussion
I needed a quick and dirty approach to splitting up jQuery multiple selectors, so I could record if a selector pattern had already been used. So I came up with this "quick 'n' dirty" hack. If someone can up with better let me know. I tried to look at the sizzle source, but didn't have enough time to plough through 2000 lines of code. // Split the following multiple selectors into an array var selector = '#nav-bar-temp-1 a, #nav-bar-temp-2 a'; console.log(getSelectors(selector)); /** * Get a list of selectors (singule or multiple) * * @param {string} selector A valid jQuery selector string * @returns {array} An array or selectors; otherwise, an empty array */ function getSelectors(selector) { var isInQuoteMark = false, // True/false when inside a quotation mark i.e. commas should be ignored isNextSelector = false, // If passed a comma set to true, so whitespace can be escaped before meeting a next non-whitespace character isQuoteMark = false, // True/false as to whether a quotation mark reQuoteMark = /[\"\']/, // Regex to determine a quotation mark selectors = [], // Array to hold found selectors temporary = ''; // Temp variable to store the selector for (var i = 0, length = selector.length; i < length; i++) { // Is it a quotation mark? isQuoteMark = selector[i].match(reQuoteMark); if (isQuoteMark && !isInQuoteMark) { // Appears to be the start of a string isInQuoteMark = true; } else if (isQuoteMark && isInQuoteMark) { // Appears to be the end of a string isInQuoteMark = false; } else if (selector[i] === ',' && !isInQuoteMark) { // If a comma and not inside a string then push to the array isNextSelector = true; selectors.push(temporary); temporary = ''; // So as not to add the comma to the temporary variable continue; } else if (selector[i] !== ' ' && isNextSelector) { // If not an empty space but the next selector has started then set to false isNextSelector = false; } // If the character can be concatanated i.e. not whitespace after a comma, then add if (!isNextSelector) { temporary += selector[i]; } } // If temporary is not empty, then push to the array if (temporary) { selectors.push(temporary); } // Return the array of selectors. Note it could be empty return selectors; }- 2 replies
-
- jquery
- javascript
-
(and 3 more)
Tagged with: