-3

Is it possible to convert a text to link by its id in CSS.

<span id="text">A text</span>

Change above text by CSS to a link like this:

<span id="text"><a href="example.org">A text</a></span>
Milad
  • 119
  • 2
  • 13
  • where is the href information ie "example.org" stored ?? before the transform – joyBlanks Aug 18 '15 at 17:49
  • 1
    No, it is not possible. You cannot create HTML with CSS. – connexo Aug 18 '15 at 17:50
  • 1
    why would you want that – joyBlanks Aug 18 '15 at 17:50
  • It is possible to make it look like a link (underline, pointer cursor), but it is not possible to make it work like a link. After all, in your example, how would the span know *where* to link? – danielaKay Aug 18 '15 at 17:50
  • Is this an [XY Problem](http://meta.stackexchange.com/q/66377)? Do you really need to make a hyperlink with CSS? Or do you actually want to know how to place a hyperlink _in JavaScript_ (because that’s the only interactive language that supports such a thing)? – Sebastian Simon Aug 18 '15 at 17:50
  • Basically a duplicate of [this question](http://stackoverflow.com/questions/9704802/css-after-element-to-insert-mailto-link) – BCDeWitt Aug 18 '15 at 17:57
  • WordPress widgets do not support links for their header titles. They accept pure text only. That's why I need to turn it to a link by css. So how can I do this without CSS. Is there other solutions? – Milad Aug 18 '15 at 17:59

2 Answers2

1

This is not possible to do via CSS

Links are considered content, which is separate from presentation (CSS). This is by design. Content like this can only be added to the page by modifying the DOM - either dynamically in the browser via JavaScript and/or by changing the HTML returned from server-side code.

To do specifically what you are asking for, you could use JavaScript like this...

const el = document.getElementById('text')
el.innerHTML = `<a href="example.org">${el.textContent}</a>`
<span id="text">A text</span>

...but this is often better:

const parentElement = document.getElementById('text')
const newElement = Object.assign(document.createElement('a'), {
  href: 'example.org',
  textContent: parentElement.textContent
})
parentElement.textContent = ''
parentElement.appendChild(newElement)
<span id="text">A text</span>

It may look more complicated than el.innerHTML='...', but this way doesn't need to be parsed, so it is the faster approach.

BCDeWitt
  • 4,540
  • 2
  • 21
  • 34
  • Ok. So how can I add a link to end of that by ":after" in CSS. When I add link with ":before" or ":after", it turns to rich text and html tags are not rendered. – Milad Aug 18 '15 at 18:19
  • As you saw, you cannot do that. `content` doesn't turn into HTML. – BCDeWitt Aug 18 '15 at 18:21
1

If you need to manipulate HTML you can do by JavaScript but there's no way to do this with css. Example

document.getElementById('your id').innerHTML = '<a href=""></a>';

You can find more here

Mohamed Saeed
  • 381
  • 2
  • 7