Ilyas karim
Ilyas karim

Reputation: 4812

How set style to a word that beings with letter #?

I am creating a tag system in my website, I want to attach CSS to words that start with letter hash (#). Can anyone tell me how to do this?

Upvotes: 0

Views: 156

Answers (3)

Ilyas karim
Ilyas karim

Reputation: 4812

Answering my own question, This can be done by following way:

html:

<p>
  #Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae aliquam, aut quod provident in incidunt quisquam perferendis aperiam ullam #quos ab ad cumque, doloremque repellat reiciendis modi sit consequuntur aliquid!
</p>

JavaScript and jQuery:

"use strict";
var allNodes,body,currentElement,currentElementString,split,splitWord,splitWord,splitLetters,stringMatch,newTag,i;

allNodes = document.body.getElementsByTagName("*");

for (i=0;i< allNodes.length;i++) {
  currentElement = allNodes[i];
  currentElementString = currentElement.innerHTML;
  split =  currentElementString.split(' ');
  for (i=0;i< split.length;i++) {
    splitWord = split[i];
    splitLetters = splitWord.split("");
    stringMatch = splitWord.match(/#/g);
    if (stringMatch == "#") {
      newTag = "<a>"+splitWord+"</a>"; 
      currentElementString = currentElementString.replace(splitWord,newTag);
      currentElement.innerHTMl = currentElementString;
      $(currentElement).html(currentElementString); 
    } 
  }
} 

and Some Css:

a {
  color: blue;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}

Upvotes: 0

Fabien Schiettecatte
Fabien Schiettecatte

Reputation: 19

You can only attach styles to DOMElements. Depending on your use case you will need to use javascript, php or another language to find words that start with a # and wrap them in a element with a class.

`<span class="my_tag">#tag</span>`

You can then use that class to add styles to this tag.

Upvotes: 2

kendepelchin
kendepelchin

Reputation: 2974

Maybe you can use the twitter-text library to parse the text and find hashtags:

see https://github.com/twitter/twitter-text

Upvotes: 1

Related Questions