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

Tips for creating a typescript module definition that exports a module dependency as one of its members

Let's consider a particular situation: I am in the process of creating typescript definitions for two commonJS modules, A and B. Module B has a dependency on module A, and to make things easier, B directly exports A as a property B.A so that users do ...

What is causing my css elements to appear larger compared to other instances?

As someone who is not a designer, I find myself doing a lot of cutting and pasting for my side hustles. I believe many others can relate to this experience. Currently, I am working on a personal project that involves using tailwindcss, appwrite, and svelte ...

Encountering an Issue: "ng new" Command Throws Error Upon Creating Angular Project

I am encountering an issue while using ng new project_name: The error message states "An invalid configuration file was found ['angular.json']. Please delete the file before running the command." I am stuck on this problem and unsure of how to ...

What is causing me to not receive a 404 error when dealing with an unhandled state?

Currently, I am utilizing $stateProvider to configure my states in the following manner: constructor($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider. state("something", { url: "/index.html" }) ...

Tips for configuring Angular 2 to send all requests in the form of application/x-www-form-urlencoded

My experience with Angular 1 has helped me in understanding how to implement a similar solution, but I'm stuck on the final step. Just like before, the backend developer for our application is set up to accept requests with type application/x-www-for ...

The file uploader on the HTML page only allows for PNG files to be uploaded

Currently, I am working on an application where I am facing a challenge related to file uploads. Specifically, I have an input field like this: <input id="full_demo" type="hidden" name="test[image]"> I am looking for a way to restrict the upload of ...

Achieve a seamless integration of a navbar and list on the same line by utilizing the power of Bootstrap

No matter how much I tried, I couldn't solve the problem of my list not appearing in the same line. I attempted using display: inline-block; and padding: 0, but to no avail. /* added by editor for demonstration purpose */ body { background-color: ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

The width of an HTML input and button elements do not match

Currently, I am facing an unusual issue where my input and button tags seem to have the same width assigned to them (width: 341.5px; calculated from $(window).width() / 4) in the code, but visually they appear to be of different widths. Here is a visual re ...

Tips for applying a class to two elements when a checkbox is clicked and avoiding duplicated URL strings

Issue with Checkbox Selection In my project, I have implemented two tabbed containers for grid and list view. Each container contains multiple elements called info boxes with checkbox inputs. Whenever a checkbox is checked, the background color of the res ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Utilization of z-index with float: left within an image gallery in CSS

Currently, I am working on an image gallery that has content generated randomly. In terms of CSS, the images are positioned using the following code: .item { width: 200px; margin: 10px; float: left; } To add some functionality, I have implemented ...

Height problem with the data-reactroot component

On one of my web pages, there is a data-reactroot element with a height of approximately 1906px. However, the surrounding divs and html tags have a height of only 915px. I am trying to figure out how to make all the enclosing elements match the same heigh ...

Unable to fetch the data from HTML input field using autocomplete feature of jQuery UI

I am facing an issue with my html autocomplete textbox. Whenever I try to enter an address like "New York" and click on the submit button, it does not retrieve the input value and returns no value. Test.aspx <!--Address--> <div class="form-g ...

Unlimited requests sent to the server while subscribing to an observable on HTTP

I am currently enhancing an Angular2 website with a feature to display the name of the user who is logged in. While I have been successful in retrieving the necessary information from the back-end service, I am encountering an issue where requests are sen ...

When a condition fails, the default style in the CSS media query does not apply

Whenever the user resizes the browser, my media query for max-width kicks in to make the design responsive. But I'm facing an issue where when the user returns back to the original browser size, the design is still a little messed up and doesn't ...

What is the best way to forward all URLs to one central page?

I've recently started working with Angular and I'm currently developing a web app project using Angular 9. I could really use your help with this. My goal is to have a dynamic URL structure for the web app, such as https://www.myMainURL.com/***, ...

What are the benefits of reverting back to an Angular 1 directive instead of using an Angular 2 application

Our team has created numerous Angular 1 components and is eager to incorporate them into our Angular 2 application. However, the documentation suggests that we must downgrade the Angular 2 application in order to integrate and utilize the Angular 1 direc ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...