user31782
user31782

Reputation: 7589

Does attr(xyz) function work on only those elements which have that particular attribute?

Consider the following code:

a:before {
  content: "(" attr(hre)")";
  color: red;
}
<a>First line <br></a>
<a hre="No Line"> This is styled with attr() function </a>

When we run the script No Line appears before the second anchor element only. But the brackets appear before both the anchor elements.

Does the attr()function work on only those elements which have that particular attribute? Is attr() defined this way?

Upvotes: 1

Views: 50

Answers (2)

BoltClock
BoltClock

Reputation: 723388

Does the attr()function works on only those elements which have that particular attribute? Is attr() defined this way?

Yes. When an attribute referenced by attr() is missing from the element, attr() returns an empty string. It does not affect the other strings you may have specified for the content property, which is why the brackets appear for both elements.

Upvotes: 2

Jay Patel
Jay Patel

Reputation: 5793

you can do this with attribute selector

a[hre]:before {
  content: "(" attr(hre)")";
  color: red;
}
<a>First line <br></a>
<a hre="No Line"> This is styled with attr() function </a>

Upvotes: 0

Related Questions