Make the text stand out by highlighting it within a div using a striking blue

Currently, I am working with Angular2 and have incorporated a div element to display multiple lines of text. Positioned below the text is a button that, when clicked, should select the entirety of the text within the div (similar to selecting text manually where it becomes highlighted in blue). Below is a snippet of my HTML:

<div #ins class="xyz" innerHTML="{{ 'sometext' | translate }}"></div>

I've attempted creating a CSS class with a background-color property set to 'blue' and applying it to the entire div upon clicking the button. However, this approach results in the entire div turning blue. My goal is to only highlight the text portion with a blue background, just as it appears when selected manually. Is there a way to achieve this effect?

Answer №1

.style {
    display:block;
    background-color:blue;
    color:#000;
}
<div class="style">Biden<br>Biden</div>

Answer №2

Consider implementing this code snippet into your HTML document:

 <div #ins id="selectedTextId" class="xyz" innerHTML="{{ 'sometext lorem ipsum' }}"></div>
 <button (click)="selectText('selectedTextId')">select</button>

Additionally, don't forget to include this method in your TypeScript file:

 private selectText(selectedElemntId):void {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById(selectedElemntId));
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(document.getElementById(selectedElemntId));
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
        }
    }

By following these instructions, you should achieve the desired result of selecting specific text on your web page.

Answer №3

Kindly find the code snippet provided below. For a live demonstration, you can visit the following Plunker link: Demo

@Component({  
   selector: 'my-app',
   template: `
    <div [ngClass]="{'yellowclass':selectedtext== true}">
      <h2>Hello {{name}}</h2>
      <h2>Hello {{name}}</h2>
      <h2>Hello {{name}}</h2>
      <h2>Hello {{name}}</h2>
      <h2>Hello {{name}}</h2>
    </div>
    <div (click)="selectedText()"> Click here</div>   `, 
}) 

export class App {  
       name:string;  
       constructor() {
            this.name = `Angular! v${VERSION.full}`
      } 
      selectedtext:boolean =false;
      selectedText(){
            if(this.selectedtext==false){
               this.selectedtext= true;
            }else{
               this.selectedtext= false;
            }
       } 
}

Answer №4

If you want to change the color of an element using JavaScript HTML DOM property, you can easily achieve it with this code:

function changeColor(){
document.getElementById("paragraph").style.background = "blue";
}
<html>
<body>

<h1 id="paragraph">This is a Heading</h1>
<button onClick="changeColor()">ChangeColor</button>
</body>
</html>

Give it a try and see if it works for your needs. Happy coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

Using CSS3 gradient in grey instead of white

I came across an amazing example by Chris Coyier showcasing a "read more" button. I attempted to replicate this by creating a simple fadeout effect from white to transparent, but unfortunately, I ended up with a grey gradient instead. You can view my atte ...

Is it possible to obtain Literal types for object keys dynamically in typescript?

I am looking to extract the type of object keys. Below is a generic function for objects with keys as strings: type GenericInput = { [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, err ...

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...

I am looking to have the datepicker automatically clear when the reset button is clicked

this code snippet is from my component.ts file resetFilters() { this.date = 0; this.query.startedAt= null; this.query.endedAt=null; this.searchTerm = ''; this.route.params.subscribe((params) => { this.machineId = Numb ...

Using Jquery to loop through a function for every select box that is added dynamically

Encountering some challenges with jQuery while attempting to utilize the same function and iterate over select boxes that are dynamically generated with jQuery's clone() method. Here is a snippet of the content being cloned: <select name="expense ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

When working with Angular and evaluating code, I encounter an issue related to the environment that

Here is my code snippet: let var1="environment.test"; console.log(eval(var1)); But when I run it, an error occurs: ERROR ReferenceError: environment is not defined However, if I modify the code to be like this: console.log(environment.test); it works ...

Having trouble applying [formControl] to a set of radio buttons in Angular2

Currently, I am encountering an issue with a list of groups of radio buttons in Angular2. My objective is to bind the value of each group of radio buttons using [formControl]. However, when implementing this, the radio buttons seem to lose their normal mut ...

The JS copy function is successful when operating on a single element, but it encounters issues when attempting to run on multiple elements, only copying

My code includes a copy function that copies the data from a textarea to the clipboard when a button is clicked. The functionality works perfectly for the first textarea, but for subsequent textareas, the buttons do not perform the copy action. Check out ...

Getting Started with CSS Alignment - A Novice's Guide

Recently, I embarked on my journey to learn HTML and CSS with the ambition of creating a login page. Although I've successfully crafted a basic version, I'm encountering an issue where the input boxes and labels are misaligned, giving off an unpr ...

Creating a Canvas Viewport Tailored for Multiplayer Gaming

Lately, I've been playing around with the HTML5 Canvas while working on an io game. However, I've hit a roadblock when it comes to handling the viewport. Setting up the viewport itself isn't too complicated, but accurately displaying other p ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Display line numbers in HTML/CSS cellsorIncor

Attempting to include row numbers in HTML/CSS. Below is the HTML code with React populating the rows: <table className="table table-striped"> <thead> <tr> {/*<th>ID</th>*/} ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...