jquery expanding the width of the final element

Is there a way to increase the width of the last 'th' in a string? I want it to be the current width plus 20px.

Here is the code on Fiddle

var header="<th id='tblHeader_1' style='width: 80px;'><span>Id</span></th>
<th class='headerSortDown' id='tblHeader_2' style='width: 300px;'><span>Title</span></th>
<th class='headerSortDown' id='tblHeader_3' style='width: 300px;'><span>Address</span></th>";


// Increase last th width
header.find('th:last').css('width', currentWidth + 20 + 'px');    
alert(header);

Answer №1

To utilize jQuery methods, try converting your header into a jQuery object using the $ symbol:

$(header).find('th:last').css('width',currentwidth+20+'px');

Remember to use ' ' for string wrapping instead of " ":

var header='<th id="tblHeader_1" style="width: 80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 300px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width: 300px;"><span>Address</span></th>';

Answer №2

To start, the first step is to convert your HTML string into a jQuery object. Then, you must retrieve the current width of the last th element before adjusting it:

var tableHeader = $(header).find('th:last');
tableHeader.css('width', (tableHeader.width() + 20) + 'px');

Answer №3

var header = $('<th id="tblHeader_1" style="width: 80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 300px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width: 300px;"><span>Adress</span></th>');
$(header[header.length-1]).css({width:"+=20"});
alert(header);

Check out the demo at http://jsfiddle.net/sBbcE/2/

Answer №4

Check out the LIVE DEMO for filter() function

Encountering an issue where JQuery's find() method is not effectively working with HTML strings. It appears that injecting it into the DOM first is necessary in order for it to function correctly.

A demonstration on how well it performs with the filter() method can be found here: Find element at HTML string

var header='<th id="tblHeader_1" style="width:80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 100px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width:100px;"><span>Adress</span></th>';

var $header =  $(header);

var th = $header.filter("th:last");

th.css('width',th.width() + 50 + 'px');

$header.appendTo('#main');

An alternative approach using the find() method.

Experience another LIVE DEMO here

var header='<th id="tblHeader_1" style="width:80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 100px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width:100px;"><span>Adress</span></th>';

var currentwidth = 100;

$('#main').append(header).find('th:last').css('background-color','red');//For Testing pu

//Increase last th width
$('#main').find('th:last').css('width',currentwidth + 50 + 'px');

Take a look at this discussion about using JQuery to search within an HTML string

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

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Guide to centering a list on a webpage using Bootstrap 3

Looking to create a centered list using the latest version of Bootstrap 3. Any tips? The desired list should be positioned in the middle of the page. ___________________________________________ | | | ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Building a custom Vue layout within Laravel UI

Currently, I am utilizing Laravel 8 along with laravel/ui 3.4 for the front end of my project. My goal is to establish a fixed sidebar, footer, and a designated area for the router-view. In my routes/web.php file: Route::view('/{any}', 'hom ...

Tips on incorporating negation in npm script's glob pattern usage?

I have been struggling to create a clean npm script that works properly. Every time I try, I either encounter an error in the console or the intended outcome doesn't occur. My goal is to remove all root JavaScript files except for certain config files ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

Issue regarding the slash format in credit card expiration dates

When entering the credit card expiration date, I am currently facing an issue. Every time I input two numbers, I need to manually add a slash (/) after them. However, if I try to delete the third number, it only removes one character. Is there a way to mak ...

Updating the data when session begins

I am having an issue with two PHP files (index.php & data.php). The first file sends data to the second file, which runs every second to display the data. However, the problem is that the data is not updating. Perhaps looking at the code will provide a be ...

Have you heard of the JQuery Accordion plugin?

I am struggling with setting the height of the content box in my accordion, which has 3 sections. I want the content to fit perfectly without any need for scrolling. Despite trying various solutions, I have not been able to achieve the desired outcome. To ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

Adding Jade template variable to an inline function

Trying to implement the JSCharts library. block content | <div id="chartcontainer">This is just a replacement in case Javascript is not available or used for SEO purposes</div> script. var myData=new Array() var myData = new Array([10 ...

When adjusting styles using Chrome DevTools with Webpack HMR, the page layout can become distorted

Encountering a peculiar issue: Currently utilizing Webpack in conjunction with Vue-CLI and HMR. On attempting to modify styles via DevTools in the browser, the page itself undergoes unexpected changes - some styles are removed (screenshots provided below) ...

Setting up module aliases in a monorepo initiated with Turborepo: a step-by-step guide

Currently working on migrating multiple repositories to the monorepo architecture using a POC bootstrapped with Turborepo. Facing an issue with misconfigured ts module aliasing. Have a single ui package where I am attempting to export a button component fr ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...

What is the best way to center the 'email promo' text in the top navigation bar alongside the image and other text links?

Struggling with learning CSS and HTML, particularly when it comes to positioning elements on the page. I'm having trouble vertically aligning the elements inside the top nav bar and can't seem to figure out what I'm doing wrong. Any insights ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

Employing the getJSON method for sending a JSON object to a PHP page while simultaneously fetching a JSON object

Currently, I am working on developing an HTML5 application that heavily utilizes JSON for data access. Several times, I need to utilize the getJSON object (with JavaScript and JQuery) to send a JSON object to a PHP page. The PHP page will then process the ...

Rotate the image as you hover your cursor over it

I am trying to implement a script where the image is rotated when the user hovers over it. Unfortunately, the hovering effect is not functioning as expected. $("#alcazar-image").rotate({ bind: { mouseover : function() { $(this).rotate({anima ...