Selectors APIã®matchesSelectorã¨ãåçãªãã¼ã¸ã§ã®ã¤ãã³ãå¦ç
Selectors APIã®Draftã«ãmatchesSelectorã¨ããAPIãå®ç¾©ããã¦ãã¦ãç¾å¨ãWebKitã¨Minefieldã®Nightlyã«æè¼ããã¦ããã
ãã ãããã©ãããªã®ã§ãã³ãã¼ãã¬ãã£ãã¯ã¹ãã¤ãã¦ãã¦ãElement#webkitMatchesSelector
ãElement#mozMatchesSelector
ã使ããªããã°ãããªãï¼ã¨ãããããã¾ã ç´æ¥ä½¿ãã«ã¯ææå°æ©ã ï¼ã
使ãæ¹ã¯ç°¡åã
var paragraphs = document.getElementsByTagName("p"); paragraphs.item(0).webkitMatchesSelector("p"); // true paragraphs.item(1).webkitMatchesSelector("div#main > p"); // <div id="main"><p>a</p></div>ãªã©ã®å ´åã¯ture paragraphs.item(2).webkitMatchesSelector("html > head"); // false
ã®ããã«ãããã¥ã¡ã³ãå ¨ä½ããè¦ã¦è¦ç´ ãã»ã¬ã¯ã¿ã«ããããã¦ããããBooleanã§è¿ãã¦ãããã
ã§ã使ãã©ãããä¾ãã°ã
<!doctype html> <html> <head><title>foo</title></head> <body> <p>hello <a href="http://example.com/">example</a>.</p> </body> </html>
ã®ãããªHTMLã§ãp > a
ãã¯ãªãã¯ããæã«ã¢ã©ã¼ããåºãå ´åã
æã ã¨ã
var anchors = document.getElementsByTagName("a"); var i; for (i = 0; i < anchors.length; i++) { if (anchors.item(i).parentNode.nodeType == Node.ELEMENT_NODE && anchors.item(i).parentNode.tagName.toLowerCase() == "p") { anchors.item(i).addEventListener("click", function (event) { confirm("æ¬å½ã«é£ã³ã¾ããï¼") || event.preventDefault(); }, false); } }
ãããªæãã«ãªã£ã¦ããã¨æãã
ã§ãquerySelectorç³»ã®APIãå
¥ã£ã¦ããã¯ã
var anchors = document.querySelectorAll("p > a"); var i; for (i = 0; i < anchors.length; i++) { anchros.item(i).addEventListener("cilck", function (event) { confirm("æ¬å½ã«é£ã³ã¾ããï¼") || event.preventDefault(); }, false); }
ãããã風ã«ãªã£ã¦ã
matchesSelectorãå
¥ã£ã¦ããã¯ã
document.addEventListener("click", function (event) { if (!event.target.webkitMatchesSelector("p > a")) return; confirm("æ¬å½ã«é£ã³ã¾ããï¼") || event.preventDefault(); }, false);
ãã®ããã«ä½¿ããããã«ãªã£ãã
matchesSelectorãå
¥ã£ã¦ããã¯ããã¯ãanchorsãèµ°æ»ãã¦ãåã
ã«ã¤ãã³ããã³ãã©ãè¨å®ãããããªäºã¯å¿
è¦ãªããã¤ãã³ãã®ãããªã³ã°ã使ã£ã¦ãã¯ãªãã¯æã«ç°¡åã«ãµããåããããããã«ãªã£ãã
ããã«ãã£ã¦ã対象ãã¼ãã大éã«ããå ´åã«ã¡ã¢ãªã¨ãã¤ãã³ããã³ãã©è¨å®æã®é度ãç¯ç´ã§ããããã«ãªãã ãã§ãªããåçã«documentã«è¿½å ãããè¦ç´ ã«å¯¾ãã¦ãèªåçã«clickã¤ãã³ãããã£ããã§ããããã«ãªã£ãï¼ãã ããmousemoveçã®é »ç¹ã«å¼ã°ããã¤ãã³ããã³ãã©ã®å ´åãåçãªãã§ãã¯ãéã«é度ãé
ãããäºãããã®ã§ã注æããªããã°ãªããªãï¼ã
å¾è
ã¯ç¹ã«éè¦ã§ãAjaxçã使ã£ãããã°ã©ãã³ã°ã«ããã¦ãåçã«è¿½å ãããã¼ãã®ã¤ãã³ããã³ãã©ãåè¨å®ããããinnerHTMLã«ä»£å
¥ããããå度ã¤ãã³ããã³ãã©ãè¨å®ããªããã°ããªã©ã¨ããäºãèããªãã¦æ¸ãããã«ãªãã
ã¨ããã§ãä¸ã§è¿°ã¹ããã¯ããã¯ã¯ã©ã¤ãã©ãªã使ãã°ä»ããã«ã§ã使ããæè¡ã§ããã
ä¾ãã°jQuery#live
ã使ããã上級レベルの jQueryã®èª¬æã詳ããã
ä»ã«ã¯ãFast Ladderããã®ãã¯ããã¯ã使ã£ã¦ãã¦ãmatchesSelectorç¸å½ã®é¢æ°ã®queryCSS
ã¨ããé¢æ°ã使ã£ã¦å®ç¾ãã¦ããã
ãã¨ãSelectorsAPI 2ã«ã¯queryScopedSelectorãqueryScopedSelectorAllã¨ããã¡ã½ãããæ°ããä½ãããããã ããã©ãããã«ã¤ãã¦ã¯ã¾ã ããã¾ã調ã¹ã¦ãªãã
åèã«ãããã¼ã¸ï¼
本の虫: matchesSelectorについて