Tom
Tom

Reputation: 4431

Is there a way to target an element depending on what is inside it?

On my page, I have custom styled hyperlinks, and I also have alot of hyperlinked images. I don't want these custom styles to appear on the hyperlinks that only contain images. Instead of adding a separate class (i.e "nostyle") to each hyperlinked image, can I somehow target the hyperlinked images from my stylesheet?

Upvotes: 2

Views: 1406

Answers (4)

dblackshell
dblackshell

Reputation:

no need for a anchor class.

a[rel="image"] img {}

Upvotes: 0

Theo.T
Theo.T

Reputation: 9267

You cannot select the parent of a matched item in CSS directly. There are workarounds with js (e.g. Searching elements and applying class attributes to their parent nodes) but seems a bit clumsy. You would rather refactor your document structure to find out a slicker solution.

Upvotes: 5

jerebear
jerebear

Reputation: 6655

Based on what it sounds like you're asking for the answer is no. You can't go backwards in the CSS only forwards.

As Theo.T mentioned, you could have a JS work-around.

One idea is to do an element innerHTML check to see if the element has an <img> tag inside it and if it does, change the element.className = "nostyle"; but that's a messy workaround and by the time you get the syntax right in JS (and cross-browser) you could have re-factored your document.

Upvotes: 0

LordOfThePigs
LordOfThePigs

Reputation: 11300

sure, just use

a img {
  // your style here...
}

if you want to target only the images within a certain class of links, use

a.yourclass img {}

Upvotes: 1

Related Questions