Is there a way to get a CSS selector on a onclick
+ function()
? You can get it on the onclick
.
Here is the HTML:
<span onclick="gotoURL("https://youtu.be/dQw4w9WgXcQ");">Rick Roll</span>
CSS:
span[onclick] {
color: blue;
text-decoration: underline;
}
But these don't work:
span[onclick="gotoURL"]
span[onclick="gotoURL()"]
The target selector is used to represent a unique element (the target element) with an id matching the URL's fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.
sure there is a way ;)
The [attribute^=value] selector matches every element whose attribute value begins with a specified value.
span[onclick^=gotoURL]
Means grab span with attribute onclick which's value is starting with gotoURL.
https://jsfiddle.net/h0qg6nys/
Cheerio :)
edit: vivekkupadhyay was faster...
edit 2: btw. you can check this for selector references https://www.w3schools.com/cssref/css_selectors.asp
edit 3: 30-css-selectors-you-must-memorize
Just clarifying what is happening with the attribute selector.
span[onclick]
selects a span which has an onclick
attribute, regardless of its value.span[onclick="…"]
selects a span whose onclick
value exactly matches something. That was your error: it didn’t match exactlyspan[onclick^="…"]
selects a span whose onclick
value begins with something. That is closer to what you were looking for.The double quotes around the something aren’t always required, but you do need them if the something contains awkward characters such as slashes. It’s always safe to include them.
Modern CSS also includes $=
which ends with a value, and *=
which contains a value. This is not available in Legacy Browsers (ie IE).
CSS is not sophisticated enough (yet) to include more interesting pattern matches, so although you can look for gotoURL
(span[onclick]^=gotoURL
), there is no way to match gotoURL()
.
Just as a side point, you really shouldn’t be using the onclick
property anyway. It’s only there for people who haven’t heard of unobtrusive JavaScript.
Shouldn't you add styling for focus maybe? It may work then. Or for an active as well.
span:focus,
span:active{
color: blue;
text-decoration: underline;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With