简体   繁体   中英

Is it possible to select an element's attribute with a CSS selector?

I'm looking for a way to use a pure CSS selector (not script) to select an element's attribute, not the element itself. I know XPath can do it but can a CSS selector?

Example, given:

<img alt="image" src="photo.jpg">

Can I get to the src attribute with a CSS selector?

Update:

I don't want to set any element's values, I just want to select the text "photo.jpg".

Because CSS selectors originated as a fundamental part of CSS, and CSS can only apply styles to elements (since attributes are just element metadata, not standalone objects), CSS selectors cannot match attributes alone within CSS.

But I suspect you're not actually asking about CSS here. You're asking about selectors alone. You're probably using a web automation tool such as Selenium or one of the numerous HTML parsing libraries out there that support either CSS selectors or XPath. Some of these libraries support non-element selectors in the form of pseudo-elements such as ::attr() (I don't remember which ones), you haven't mentioned which tool you're using so I can't tell you for sure if you could use it. Note that this is not the same thing as the CSS attr() function mentioned in the comments — that is a CSS function, which is a value, not a selector, and therefore it cannot be used in a selector.

But if your library doesn't have such a feature then you'll need to either select the img element directly and query its src attribute separately (again, how you do this depends entirely on what you're using, which is why it helps to be specific about this sort of thing), or use XPath if possible.

CSS Tricks has an article that I believe answers your question: https://css-tricks.com/almanac/selectors/a/attribute/

If you are trying to set the value of a certain element attribute using css, I'm pretty certain that is impossible for anything other than the content property.

CSS is not a programming language and can't process data.

Its sole purpose it to tell the browser how a certain element should look like, like in coloring a text red.

To process data in a web page you use javascript, which can make use of CSS rules though, to grab a certain type of elements in a web page, for example this, which will return a list of all elements of type img

var imglist = document.querySelectorAll('img');

Now, having a list you can loop through it and get each src like this

Array.prototype.slice.call(document.querySelectorAll("img")).forEach(function(img) {

    var imgsrc = img.src;

    // imgsrc now holds the image url, in your case "photo.jpg"

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM