More often than not I find myself using only few jQuery selectors to locate elements in DOM for event binding; however, jQuery also offers some powerful psedo-RegEx selectors for locating elements.
Say, you have the following HTML5 markup:
--------------------------------------------------
You can use the following selectors to locate the "article-header" element.
1- Using closest
$(".post-article").closest("header").first()
2- If DOM is properly ordered
$(".post-article").firstChild()
3- Using psedo-RegEx expressions
The general parttern for using psedo-RegEx expressions is as follows:
$("[atttr{selectorExpression}{selectorText}]")
Where:
attr - Is the attribute of the DOM element (e.g class, id, style, name, etc...)
selectorExpression - Is the RegEx expression (e.g. ^ for starts with, ~ for contains, ! for not)
selectorText - is the text that is used in the DOM element
Using the example above:
To select the "article-header" element you can use the "equals to" selector as follows:
$("[class=article-header]")
or if the class name starts with "article-header," you can use the "starts with" operator as follows:
$("[class^=article-header]") or $("[class~=article-header]") for contains operator.
Alternatively, if you are only interested in elements other than the "article-header" element. You can use the "not" operator as follows.
$("[class!=article-header]")
Here is a complete list of jQuery selectors:
Say, you have the following HTML5 markup:
--------------------------------------------------
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery Selector</title> </head> <body> <article class="post-article"> <header class="article-header"></header> <p class="article-content"></p> </article> </body> </html>
--------------------------------------------------
You can use the following selectors to locate the "article-header" element.
1- Using closest
$(".post-article").closest("header").first()
2- If DOM is properly ordered
$(".post-article").firstChild()
3- Using psedo-RegEx expressions
The general parttern for using psedo-RegEx expressions is as follows:
$("[atttr{selectorExpression}{selectorText}]")
Where:
attr - Is the attribute of the DOM element (e.g class, id, style, name, etc...)
selectorExpression - Is the RegEx expression (e.g. ^ for starts with, ~ for contains, ! for not)
selectorText - is the text that is used in the DOM element
Using the example above:
To select the "article-header" element you can use the "equals to" selector as follows:
$("[class=article-header]")
or if the class name starts with "article-header," you can use the "starts with" operator as follows:
$("[class^=article-header]") or $("[class~=article-header]") for contains operator.
Alternatively, if you are only interested in elements other than the "article-header" element. You can use the "not" operator as follows.
$("[class!=article-header]")
Here is a complete list of jQuery selectors:
Comments