Ways to modify or add styles to p tags using the Document Object Model (DOM)

I am trying to change the font size variable in my P tag using the DOM, but I am struggling to find a way to access it and modify the styles. I attempted the following code:

document.body.p.style.font-size = ""+p_var+"px";

I have also tried using various methods like setAttribute, but so far, I have had no success. Can someone please demonstrate how to change the font size variable if it is possible?

Answer №1

Check out this snippet:

let paragraphs = document.getElementsByTagName('p');
for(let i=0; i<paragraphs.length; i++)
{
    paragraphs[i].setAttribute("style","font-size:"+fontSize_var+"px");
}

View Demo on JSFiddle

Answer №2

Here is an example you can use:

<p id="myText">This is some text.</p>

JavaScript:

document.getElementById("myText").style.fontSize = ""+textSize+"px";

If you want to apply the style to all <p> tags, you can try this:

var elements; 
elements = document.getElementsByTagName('p');
for (var j = elements.length-1; j>=0; j--) {
    elements[j].style.fontSize = ""+textSize+"px";
}

Alternatively, if you have <p> tags with the same class name like below:

<p class="textClass">This is some text.</p>
<p class="textClass">This is some text.</p>

You can use this code:

var elements; 
elements = document.getElementsByClassName('textClass');
for (var k = elements.length-1; k>=0; k--) {
    elements[k].style.fontSize = ""+textSize+"px";
}

Answer №3

To achieve this using jquery, you can use the following syntax:

$("p").css({"font-size":"30px"});

Answer №4

To begin, set up a CSS class as shown below

.largeText {
  font-size: 30px;
}

Next, use jQuery to apply the class

$("p").addClass("largeText");

Using classes is a better approach than inline CSS styling :)

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

Creating dirty or touched input programmatically in Angular2 can be achieved by using the `.markAsT

Looking to integrate a JQuery plugin with Angular2? Essentially, this plugin generates a duplicate of specific HTML content containing inputs. As data is modified, Angular2 automatically re-renders the content along with any errors. However, the challenge ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

Tips for effectively deleting a flash object from an HTML page

I recently created a website with AJAX (using jquery) for navigation purposes. The pages on the site slide smoothly, and I have been using remove() to get rid of the old page. Everything was working fine until I encountered an issue where the browser cras ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

How to style a webpage to be printed in CSS with A4 dimensions

Whenever I try to print my webpage, I encounter an issue where everything changes on the printout. I would like to be able to print a webpage that looks exactly like what is displayed on the screen. Here is an example of what I am looking for: enter imag ...

employing the CSS `:empty` pseudo-class to conceal an element

Upon using chrome for inspection, I stumbled upon the following code snippet: <div class="entry-content"> <p>We .... </p> </div> <footer class="entry-footer"> </footer> Occasionally, this f ...

What steps should I follow to obtain code coverage data in my Aurelia application with the help of karma?

After creating my Aurelia app using the Aurelia CLI (au new), I wanted to set up code coverage, preferably with karma-coverage, but was open to other options as well. First, I ran npm install karma-coverage --save-dev and then copied the test.js task over ...

Transforming BufferGeometry to Geometry using FBXLoader within the Three.js library

Check out my snippet below for loading a .fbx object. It defaults to loading an object as BufferGeometry: const loader = new THREE.FBXLoader(); async function loadFiles(scene, props) { const { files, path, childName, fn } = props; if (index > fi ...

Is there a way to expand a pie chart into a new pie chart with PHP and Javascript?

I need help finding a code that can expand a pie chart into another pie chart. The original pie chart appears too congested with numerous entries when it first loads. I have only come across tutorials for accomplishing this in Excel online. Can someone a ...

What is the best way to create a video that takes up the entire height of a half-sized

page url: I am facing a challenge with displaying a video that has dimensions of 4096x2160 pixels. I want to show the centered part of the video with full height on my left half screen. Despite trying various methods, I have not been able to find a suita ...

Error encountered while trying to install discordjs with npm

npm encountered an error with code 1 while trying to install windows-build-tools: Error occurred in command: C:\WINDOWS\system32\cmd.exe /d /s /c node ./dist/index.js Python MSI and BuildTools_Full.exe were successfully downloaded but the ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

changing session variables in JavaScript

My index.php page contains all my PHP functions, JavaScript code, and HTML tags. I am trying to figure out how to call a PHP function (addToCart($itemID)) to update session variables when the user clicks on a button (add to cart). Can you provide guidanc ...

Passing a value from a prop to a click event that is dynamically created within an SVG Vue.js

Currently, I am in the process of developing a map component using a JSON array and implementing a click event handler for each item. The objective is to toggle the CSS style to color the item when clicked, which is functioning as expected. However, my goa ...

Different ways to initialize objects in JavaScript (constructor overloading)

Within my Account_Model.js model, I have a set of queries that handle creating, reading, updating, and deleting user accounts (CRUD operations). The constructor I currently have requires passing in parameters such as username, fullname, and password for cr ...

Simultaneous beforeSave actions permitting repetitions

To prevent certain objects from being created, I incorporated a conditional in the beforeSave cloud function of that object type. However, when two objects are created at the same time, the conditional fails to work as expected. Check out my code snippet ...

Is there a way to monitor and trigger a function in jQuery when a loaded PHP file is modified?

I am currently working on a dynamic dashboard that automatically updates every few seconds to display new information fetched from a PHP file. My goal is to trigger an alert only when there is a change in the data itself, rather than just a refresh. In ord ...

How to remove previous and next buttons in product carousel using Bootstrap 3.3.5

Currently, I am tackling a small project and venturing into the world of bootstrap for the first time. I have hit a roadblock when it comes to disabling (not hiding) product carousel controls when the active state is on the item:first & item:last classes. ...

potential issues with memory leakage and browser crashes in three.js

Currently working on an app that features a spherical panorama photo with a jpg size of around 4Mb. Throughout the development process, I find myself constantly refreshing the page to see changes and browsing through various three.js example pages for insp ...

Unable to bind knockout dropdownlist data during an ajax request

Trying to connect a dropdownlist in knockout with MVC 4. Below is the code snippet: Action public JsonResult GetUserTypes() { using (QuestApplicationEntities db = new QuestApplicationEntities()) { var usertypes = (from ...