What is the best way to format changing text within a paragraph?

If I needed to implement this functionality using JavaScript:

......
if (!isNaN(num))
    document.getElementById("isNum").innerHTML = num +" is a number";
......

Then in HTML :

<div>
    <button onclick="checknum()">Enter any value : </button>
    <p id="isNum"></p>  
</div>

The expected output (for input "3"):

3 is a number 

The query being posed is:

How can I highlight, perhaps via CSS, the variable within Javascript to display the output as follows:

3 is a number

Answer №1

To enhance the appearance of your number, consider enclosing it in a span:

document.getElementById("isNum").innerHTML = '<span>' + num + "</span> is a number";

You can then apply a specific CSS style to this span within the paragraph with the id #isNum:

#isNum span{
    font-weight: bold;
    color: green;
}

We hope this solution proves helpful.

var num = 3;

if (!isNaN(num))
    document.getElementById("isNum").innerHTML = '<span>'+num+"</span> is a number";
#isNum span{
    font-weight: bold;
    color: green;
}
<div>
    <p id="isNum"></p>  
</div>

Answer №2

It would be more suitable to emphasize the input using <em> in this scenario.

<p id="isNum"><em>3</em> is a Number</p>

Below is a sample code snippet (hopefully, it is easy to understand).

The concept is to enclose the value that needs emphasis within an inline element (such as span or em).

Keep in mind that <b>, i, or <em> elements can also achieve similar results.

function checknum() {

  // Reference the `output` element
  var outputElement = document.querySelector("#isNum");

  // Retrieve the input value 
  var num = document.querySelector("#numValue").value;

  // Check: do we have a value and is it a number?
  var isNumber = num.length > 0 && !isNaN(num);

  // Format the HTML string for outputting
  // Wrap the value inside an inline element for separate styling
  var outputHTML = "<em>" + num + "</em>";

  // Output result
  outputElement.innerHTML = isNumber ?
    outputHTML + " is a number" :
    "Not valid";
}
#isNum > em {
  color: blue;
}
#isNum > span {
  /* if using span */
  font-weight: bold;
  font-style: italic;
  color: blue;
}
<div>
  <input type="text" id="numValue" />
  <button onclick="checknum()">Insert anything</button>
  <p id="isNum"></p>
</div>

Answer №3

document.getElementById("isNum").innerHTML = "<span style='color: blue;'>" + num +"</span> is a digit";

Alternatively (and this is often seen as a more recommended approach) you could assign a class to the span element instead of using inline styling. Then, specify the color for that class in your CSS file.

JavaScript:

innerHTML = "<span class='digit'>" + num +"</span> is a number";

CSS:

.digit { color: blue; }

Answer №4

Give this a shot:


   if (num && typeof num === 'number')
    document.getElementById("isNumber").innerHTML = '<span class="highlight">' + num +"</span> is indeed a number";

Answer №5

To display the number in HTML, you must enclose it with a certain element

Imagine that this is how the HTML appears on the page

<p id="isNum"><span class="num-color"> 1</span> represents a color</p>

next, apply some CSS

.num-color {
 color: yellow;
}

If you want to see the mentioned HTML output, adjust your JavaScript code as follows:

document.getElementById("isNum").innerHTML = '<span class="num-color">' + num + '</span>' +' represents a number';

Answer №6

Just insert an element

element.innerHTML = "<span class='blue'>" + num +"</span> represents a numerical value";

Then, modify the styling of that class

function validateNumber() {
  var num  = prompt('Please enter a number');
  var element = document.getElementById("isNum");
  
  if (!isNaN(num))
    element.innerHTML = "<span class='red'>" + num + "</span> is a number";
}
.red {color : red}
<div>
    <button onclick="validateNumber()">Enter a number: </button>
    <p id="isNum"></p>  
</div>

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

The Redux UI does not refresh when altering the state of a nested array

As someone who is relatively new to Redux, I am facing an issue with my web application which is an eCommerce platform. In this application, users can create multiple carts, each with a unique id and name, and add different items to these carts stored in a ...

Adapting my JavaScript code to handle one-dimensional CSV data instead of the usual two-dimensional format

How can I effectively parse this CSV file using JavaScript? 1363085391,42.890000000000,5.432200000000 1363088879,47.570000000000,4.981800000000 1363120475,56.560000000000,1.768000000000 1363132522,53.000000000000,1.000000000000 1363214378,48.630000000000, ...

Combining various data types within a single field in BigQuery

Is it feasible to specify a table schema with a field that allows for multiple data types? For instance: BIGQUERY TABLE SCHEMA schema: [{ name: 'field1', type: 'string', }, { name: 'field2', type: &apo ...

The $_REQUEST variable is functioning properly, while the $_POST variable seems to

I currently have an HTML form using the post method. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript& ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

Steps to prevent cart resizing in desktop view:

For a front-end challenge, I need you to design a simple card that displays consistently in both mobile and desktop views. I took a mobile-first approach because I've encountered issues where the card layout changes when viewed on desktop. Check out ...

Determining the page's coordinates in ColdFusion

Whenever I use iframes or frames on older websites, I implement an additional security measure using a JavaScript function: <SCRIPT LANGUAGE="JavaScript1.1"> if (top == self) self.location.href = "../index.cfm"; </SCRIPT> I also include an ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Entry module could not be located due to an unresolved 'babel-loader' error

As a newbie to the world of React, I found myself facing an issue while setting up the installation and loading all the necessary dependencies. Upon running the npm start command, I encountered the following error message: ERROR in Entry module not found: ...

Strategies for maintaining a sticky element while transitioning between containers

My challenge involves a sticky button located inside a container, but the sticky behavior only seems to work within another element that is full width (container-fluid). Is there any way to make the sticky behavior global? I have attempted using 'fix ...

Restricting the embedding of my website to a select few domains

Looking to embed my web app on various websites, but I want to restrict access based on domain. For example, allowing and to embed without issues, while blocking . Is there a way to achieve this? Using iFrames for the embedding process. ...

The functionality of mouse hover in multimaterial three.js appears to be not functioning

I'm facing an issue where I want to create a mouse hover effect on an object with multiple materials. See an example here function update() { // Finding intersections // Creating a Ray with the origin at the mouse position // and dire ...

Obtain image file paths dynamically in a folder using Nuxt

https://i.sstatic.net/3FKZH.png Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing im ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Creating PDF files from elements using Puppeteer JS

In my quest to master the usage of Puppeteer within a Vue.js application, I am facing a challenge. I am able to create a PDF based on the entire page successfully, but I am struggling to generate a PDF for a specific element on the page. Is there a method ...

How to adjust background size for Iphone4 and Iphone5 simulators using only HTML5 and CSS3 code

Creating an HTML5 app for iPhone4 and 5 with a texture-rich background. I'm facing an issue where the texture image gets scaled and only the central part is visible, even though the image size is 640x960 and 640x1136. I've tried adding @2x at the ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...