plrthink
plrthink

Reputation: 311

How to change style of a arbitrary part of html text

I want to change style on part of text on arbitrary position with arbitrary length. For example, I have this in my html

<span id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.<span>

Given variables start and length, which could be any valid value I don't know, I am supposed to change color of specific text.

How can I achieve this task?

Upvotes: 0

Views: 401

Answers (4)

user3497034
user3497034

Reputation:

Try following code. It should work:

<!DOCTYPE html>
<html>
  <head>
<meta charset="UTF-8">
<style>
  .Inlinetext{ color:red;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
  function ChangeTextColour(start,end){
    var startingHtml = "<span class='Inlinetext'>";
    var endingHtml="</span>";
    var middleHtml=$("#Inlinetext").html().substring(start, end);
    $("#Inlinetext").html($("#Inlinetext").html().substring(0, start)+startingHtml+middleHtml+endingHtml+$("#Inlinetext").html().substring(end));
  }
</script>

  </head>
  <body onload="ChangeTextColour(3,100)">
<span id="Inlinetext">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
  </body>
</html>

You just needs to mention starting and ending position of string which will change style sheet. If you wish multiple style sheet, then use in CSS tag.

Upvotes: 1

captainsac
captainsac

Reputation: 2490

You will ahve to insert another span inside this span dynamically. I have written the following code in javascript to do the same. Hope it will help you.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .text{ color:red;}
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
      function ChangeColor(start,end){
        var newStartHtml = "<span class='text'>";
        var newEndHtml="</span>";
        var midHtml=$("#text").html().substring(start, end);
        $("#text").html($("#text").html().substring(0, start)+newStartHtml+midHtml+newEndHtml+$("#text").html().substring(end));
      }
    </script>

  </head>
  <body onload="ChangeColor(3,15)">
    <span id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
  </body>
</html>

Upvotes: 0

Pramodh Valavala
Pramodh Valavala

Reputation: 752

Here is a plain javascript implementation of what you need.https://jsfiddle.net/ewgsyn10/

In case you want to apply css to that specific section, you could use <span class="your-css-class"> instead of <b> and similarly for the closing tag.

Upvotes: 0

veerasuthan V
veerasuthan V

Reputation: 330

find the string that you want to match and replace it with span wrapper and highlight it.

http://bartaz.github.io/sandbox.js/jquery.highlight.html this is the sample plugin

Upvotes: 0

Related Questions