AlwaysLearning
AlwaysLearning

Reputation: 81

Can I select all elements whose attribute names (not values) start with a certain string?

Say that I have this markup excerpt:

<p onblur="...">text 1</p>
<p class="myclass">text 2</p>
<p onfocus="...">text 3</p>

Is there a CSS selector that I could use to get the first and last elements (but not the middle) using the fact that they both have attributes that start with 'on'? I'm looking for a general solution rather than something for this particular case (since, of course, the intended outcome could be achieved in much more straightforward ways for this particular example).

A Javascript-based solution would work fine for me too (though I'm hoping to avoid the brute force examine-every-element approach). That's actually what I'm looking for (a selector that can be used with jQuery or a similar library).

Upvotes: 1

Views: 203

Answers (2)

Esailija
Esailija

Reputation: 140210

As pointy pointed out, this isn't the recommended way of going around things. Simply use a class to group elements that you want to target at once.

However, you can target most event handlers with this:

[onabort],[onbeforecopy],[onbeforecut],[onbeforepaste],[onblur],[onchange],[onclick],[oncontextmenu],[oncopy],[oncut],[ondblclick],[ondrag],[ondragend],[ondragenter],[ondragleave],[ondragover],[ondragstart],[ondrop],[onerror],[onfocus],[oninput],[oninvalid],[onkeydown],[onkeypress],[onkeyup],[onload],[onmousedown],[onmousemove],[onmouseout],[onmouseover],[onmouseup],[onmousewheel],[onpaste],[onreset],[onscroll],[onsearch],[onselect],[onselectstart],[onsubmit] {
  color: #BADBAD;   
}

See demo http://jsfiddle.net/uwXgt/1/

Upvotes: 1

theabraham
theabraham

Reputation: 16360

There is a CSS selector to choose based on element attributes:

p[onfocus] { color:blue; }
p[class=myclass] { color:red; }

But there's no way in CSS to choose based on the first part of the attributes name.

Upvotes: 0

Related Questions