Select HTML node by attribute with dommy
-
21-12-2019 - |
Question
Using dommy in ClojureScript, how do you make a node selection by attribute? For example, in jQuery this would look like $('tr[data-id=1]')
. I tried (sel1 "tr[data-id=1]")
but I got this error:
Uncaught SyntaxError: Failed to execute query: 'tr[data-id=1]' is not a valid selector.
Is this possible with dommy? If not, what's the best alternative in ClojureScript? jayq?
Sample HTML:
<table>
<tr data-id="1">
<td>Cow</td>
<td>Moo</td>
</tr>
</table>
Solution 2
Dommy uses document.querySelectorAll
under the hood, which requires the attribute's value in the selector to be in quotes.
(sel1 "tr[data-id='1']")
If you don't want to use quotes, there are at least two simple alternatives:
goog.dom.query is already available as a dependency in ClojureScript and it supports attribute selection.
(ns example
(:require [goog.dom.query :as query]))
(query "tr[data-id=1]")
jayq is a wrapper for jQuery. Add [jayq "2.5.0"]
to your project.clj
to use it.
(ns example
(:require [jayq.core :refer [$]]))
($ "tr[data-id=1]")
(Thanks to yonki for pointing out the quotes are necessary.)
OTHER TIPS
Chill out guys, it’s possible easily. Check this code:
(sel1 "tr[data-id=\"1\"]")
Have a look at your HTML code <tr data-id="1">
. You see that data-id
value is in quotation marks. You just have to include quotation marks in your selector and everything gonna be ok. \"
is escaped quotation marks. Hope that’s fairly understandable.
Lastly: Dommy uses querySelectorAll
when needed, so you can use every CSS selector that browser is capabale of recognizing.
this approach can work also!
(ns dosync2.core
(:require [dommy.utils :as utils]
[dommy.core :as dommy]
[dommy.attrs :as dattr])
(:use-macros
[dommy.macros :only [node sel sel1]]))
(defn select-by-tag-and-attr-value [the-tag the-attr the-attr-value]
(let [tag-selection (sel the-tag)]
(filter #(= the-attr-value (dattr/attr % the-attr)) tag-selection)
)
)
(. js/console (log (clj->js (select-by-tag-and-attr-value :tr :data-id 1))))