Shells Be Shells Be - 7 months ago 16
Javascript Question

ClojureScript: Using Jayq to get value of attribute

I was wondering if anyone knows how you can get the value of an attribute from a webpages HTML using jayq in ClojureScript.

I have done this so far:

(ns jquerytest.core)

(def jquery (js* "$"))
(jquery
(fn []
(-> (jquery "#w3s")
(.attr "href" "http://www.duckduckgo.com")
)
)
)


This code does what it should and changes the "href" value in the attribute "w3s" from http://www.google.com to http://www.duckduckgo.com.

From what I know of jQuery (on which jayq was wrapped around), getting the value of an attribute is as simple as:

var hyref = $(this).attr('href');
alert(hyref);


So, I've been trying to model a similar behavior in my clojurescript (but simply writing to the screen etc). Here is a set of two example attempts:

(1)

(defn attr-link []
(doto (jquery ".link")
(.html)
(println)
)
)


This method was only to see if I could get anything from the attribute "link" at all, I did manage to get this printed out to the screen:

function jquerytest$core$y(){ var G__6988 = jquerytest.core.jquery.call(null,".link"); G__6988.html(); cljs.core.println.call(null,G__6988); return G__6988; }


(2)

(defn getVal []
(-> (jquery "#w3s")
(.attr "href")
)
)


I was hoping that someone might be willing to point out my own stupidity by talking me through how to one should actually go about doing this.

Answer

So after a while of searching, I managed to stumble upon the answer myself. Using the Dommy library (dom in my code) I managed to retrieve the href value of a "a" tag.

  (ns hello-world.core
  (:require [clojure.browser.repl :as repl] [dommy.core :as dom])
      (defn get-link-value 
        []
        (println (-> (dom/sel1 "#my-link")
          (dom/attr :href)
        )   
      )

This is by no means probably the best solution to the problem, but it is the only one I managed to find at this time.