Home > OS >  Target <h3> text by internal sibling <a> tag id
Target <h3> text by internal sibling <a> tag id

Time:12-27

So I am using a rust markdown parser and it renders header_ids by placing an <a> tag with an id inside the <h> tags.

So I am getting something like:

<h3>
  <a href="/" id="SOMEID"></a>
  "TEXT"
</h3>

So I want to color the text thats in the <h3> tag by target it by the id thats on the <a> tag. So not target the directly because then I would color all the <h3> tags.

I tried some different css selectors and what not to target it, but nothing worked. Not even sure if thats possible.

CodePudding user response:

you can try something like that:

h3:has(> #test) {
color: red;
}
<h3>text</h3>
<h3>text <a id="test" href="#">text</a> text</h3>

CodePudding user response:

Although you can achieve that with some CSS it's not the correct way to do it. IDs should only be used for specific cases or not at all in my opinion. It's fine to use an ID for some Javascript selectors due to performance but for CSS seems like and over kill.

If you want to have the H3 having one color and the A tags inside it just do:

h3 {
  color: black;
}

h3 > a {
  color: red;
}
<h3>
This is a title
</h3>

<h3>
This is a title <a href="/">with some anchor</a>
</h3>

If you want only that particular A tag of that H3 to change color, then use a class instead like so:

h3 {
  color: black;
}

h3 > .anchor {
  color: red;
}
<h3>
  This is a title
</h3>

<h3>
  This is a title <a href="/" >with some anchor</a>
</h3>

If you are using an ID in order to create an anchor link to that ID that's fine, but you should not use CSS selectors to attribute CSS Styles to something as trivial as an A tag.

CodePudding user response:

If JavaScript isn't out of scope, you can query regularly for h3 a and then use the parentElement to assign the styling:

const linksWithH3 = document.querySelectorAll("h3 a");

for(let index = 0; index < linksWithH3.length; index  ) {
  const parentElement = linksWithH3[index].parentElement;
  
  parentElement.style.color = "red";
}
<h3>
  <a href="/" id="SOMEID"></a>
  "TEXT"
</h3>

Or you can introduce a class:

const linksWithH3 = document.querySelectorAll("h3 a");

for(let index = 0; index < linksWithH3.length; index  ) {
  const parentElement = linksWithH3[index].parentElement;
  
  parentElement.classList.add("h3-with-a");
}
.h3-with-a {
  color: red;
}
<h3>
  <a href="/" id="SOMEID"></a>
  "TEXT"
</h3>

  • Related