Jquery css bold text

Style fontWeight Property

The fontWeight property sets or returns how thick or thin characters in a text should be displayed.

Browser Support

Syntax

Return the fontWeight property:

Set the fontWeight property:

Property Values

Value Description
normal Font is normal. This is default
lighter Font is lighter
bold Font is bold
bolder Font is bolder
100
200
300
400
500
600
700
800
900
Defines from light to bold characters. 400 is the same as normal, and 700 is the same as bold
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

More Examples

Example

A demonstration of possible values:

var listValue = selectTag.options[selectTag.selectedIndex].text;
document.getElementById(«demo»).style.fontWeight = listValue;

Example

Return the font weight of an element:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Как сделать жирный текст (шрифт) в HTML/CSS/jQuery/JavaScript?

Жирный текст (или какие-то отдельные его части) часто используется для того, чтобы выделить главную мысль текста или заострить на этом участке внимание пользователя.

Для разных случаев есть разные варианты решения поставленной задачи, поэтому о каждом – немного подробнее.

Жирный текст (шрифт) в HTML

Начнем, пожалуй, с классики – чистого языка разметки HTML (я думаю, что вы помните, что HTML – не язык программирования).

В HTML для того, чтобы сделать нужное слово (фразу или целый текст, хотя для больших объемов данных рациональнее использовать CSS. О нем чуть ниже) жирным, существует два тега.

Первый – это тег . Текст, вложенный в него, становится стандартным полужирным. Использование:

Закрывающий тег обязателен. Не имеет персональных атрибутов, только универсальные, по типу id, class и прочих.

Второй – тег . Использование:

 Hello, World!

Закрывающий тег, значение насыщенности (жирности) и атрибуты – все как в предыдущем теге.

Существенное отличие тега от в том, что первый () является элементом логической разметки и используется для указания важности заключенного в него текста, когда как второй () – элемент физической разметки и просто изменяет внешний вид текста (также заключенного в него).

Чтобы убрать жирность текста, заключенного в один из этих тегов, просто удалите их (эти теги) или воспользуйтесь свойством CSS.

Жирный текст (шрифт) в CSS

В каскадных таблицах стилей (CSS) насыщенность (жирность) текста устанавливается с помощью свойства font-weight. Популярными значениями (на мой взгляд) являются 400 (эквивалент normal, обычный вид текста) и 700 (эквивалент bold, стандартный полужирный).

Все допустимые значения свойства находятся в диапазоне от 100 до 900 (включительно) с шагом 100 (100, 200, 300, 400 или normal, 500, 600, 700 или bold, 800 и 900). Некоторые из этих значений могут не дать желаемого результата из-за особенностей используемого шрифта.

Помимо этого, существуют значения bolder и lighter (они задают жирность указанного текста относительно родителя, в большую или меньшую сторону соответственно), а также inherit (указывает на наследование значения от родителя) и initial (установка значения по умолчанию).

Жирный текст (шрифт) в jQuery/JavaScript

Если вы хотите задать некому тексту необходимую жирность с помощью jQuery или JavaScript, то можно пойти двумя путями. Первый – это обернуть текст при его вставке на страницу, используя HTML-теги.

Аналогичный вариант на JavaScript:

Второй – это применить свойство font-weight из CSS с нужным его значением:

  

Аналогичный вариант на JavaScript:

  

Плюсом, существует метод bold(), который оборачивает переменную (текст) в HTML-тег :

 var str = "Hello, World!"; var text = str.bold(); // Hello, World!

Хотя, если верить некоторым источникам, этот метод считается устаревшим и не рекомендуется к использованию.

Источник

Make bold text inside element (jQuery)

Solution 4: Question: I have a jquery that changes the text of a link like so: And html: I am trying to add bold to this link, but adding leaves them escaped in the text itself, rather than making the text bold Solution 1: sets string as HTML content, whereas sets the string as text. Solution: Using regex, you can select text between parentheses and wrap it with tag to showing bold.

Make bold text inside element (jQuery)

I’m trying to make text (fat) bold. Curretly I managed to do this whit code below:

Movie fat was been added 

But this bold tags won’t work. Now the question is how to enable html for only (fat), to be bold like this: Movie fat was been added

var boldy = (Movie[0].title) var fat = boldy.bold() $("div.container div:first").text("Movie " + (fat) + " was been added") 
$("div.container div:first").html("Hello "+(boldy)+"") 
var word ="fat" $("div:first").html("Movie "+word+" was been added")

You can use the following:

$("div.container div:first").css("font-weight","Bold"); 

That will change the property font-weight from that div to bold .

@EDIT: You can make a div with an ID and set that ID on the jQuery mention:

$("div.container div:first div#text").css("font-weight","Bold"); 
var world = 'world'; $("div").html(`Hello $ `);
var html = $("div.container div:first").html; $("div.container div:first").html(html.replace(/fat/gi, '$& ')); 

How to make matched text bold with jquery ui, I am wondering how to make the matched part of the autocomplete suggestions bold when using jquery ui autocomplete? So for example if you type in «ja» and the suggestions are javascript and java (like in the example on the jquery ui demo page) then I would like to make «ja» bold in both suggestions. Anyone …

Jquery $(‘id’).text with Bold

I have a jquery that changes the text of a link like so:

 I am trying to add bold to this link, but adding More Info leaves them escaped in the text itself, rather than making the text bold

.html() sets string as HTML content, whereas .text() sets the string as text.

Or if you wanted to get extravagant (and somewhat unnecessary):

The text() method inserts text, while the html() method inserts HTML, and tags are HTML

You can keep your .text() method by simply adding the style via the .css() method:

See working jsFiddle demo

How to make text bold, italic and underline using jQuery, To make text bold, italic and underline using jQuery, use the jQuery css () method with the CSS properties font-style, font-weight and text-decoration. You can try to run the following code to learn how to make text bold, italic and underline using jQuery − Example Live Demo

Selected text and making bold apart from first word using jQuery

I know this is something very simple but I am still new to jQuery, so I’m a little unsure how to approach. I have found a good few solutions with making the first word bold but not what I need.

I want to only make the words bold other than the first word; is this possible?

Buy This Product

I only have a example from another solution for the first word but not sure how to adjust.

$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h)< return h.replace(/\w+\s/, function(firstWord)< return '' + firstWord + ''; >); >); 

I have adjusted with the classes I need and the find class but I want to make the text but excluding the first word.

There are a few ways to do this. You could use a regex like / (.*)/ to match the first space followed by every other character to the end of the string as a sub match:

$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h)< return h.replace(/ (.*)/, " $1"); >);

Note that using parentheses in the regex allows you to refer to the matched bit using $1 , so you can provide the replacement as a string in the second argument to .replace() rather than passing a function.

How to display a particular word in bold using jquery?, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

How to make text between parentheses bold using javascript/jquery?

I want to bold text between parentheses using jQuery / JavaScript. i.e.

Text between parentheses should be bold using jQuery or JavaScript. Can anyone help me?

Using regex, you can select text between parentheses and wrap it with tag to showing bold.

Css — Find text string in jQuery and make it bold, Find text string in jQuery and make it bold. What I want to do is use jQuery to find a piece of text within a paragraph and add some CSS to make it bold. I can’t seem to figure out why this won’t work: $ (window).load (function () < // ADD BOLD ELEMENTS $ ('#about_theresidency:contains ("cross genre")').css (

Источник

‘How to animate text with css font-weight property in jQuery ? normal to bold

EDIT, April 2021: This is now possible to achieve either with transition: font-weight or more seamlessly with variable fonts.

Sadly I think this is impossible.

Each character in a font has a specific shape. In addition, similar characters in different weights weights are also distinct—a bold character does not simply have a mathematically-defined offset from its regular counterpart.

It would be very easy to jump from regular to bold or italic with jQuery.css(), but there it is currently impossible to jQuery.animate() the transition of font-weight in the browser. It is hard to do in animation as well because there are no “frames” between the different weights, as they are all drawn separately.

However,

If you choose a font that has a consistant spacing of letters for the different weights—such as Exo—and do a stepped animation from thin to black you might come close to the desired result.

Starting from your jsFiddle that is what I could come up with:

And the rather dumb Javascript behind it:

Text.click(function() < Text.css(); setTimeout(function()< Text.css()>, 30) setTimeout(function()< Text.css()>, 60) setTimeout(function()< Text.css()>, 90) setTimeout(function()< Text.css()>,120) setTimeout(function()< Text.css()>,150) setTimeout(function()< Text.css()>,180) setTimeout(function()< Text.css()>,210) >); 

Solution 2: [2]

You could use pure CSS, using text-shadow and the pseudo class :hover , with a transition to animate it

Also you could use jQuery, by using addClass() :

.animate < font-size: 30px; >/* Then .bold CSS class */ .bold

Or, if you wanted a toggle effect, using a ternary operator:

($(".animate").hasClass("bold")) ? $(".animate").removeClass("bold") : $(".animate").addClass("bold"); 

Solution 3: [3]

You can check it in action on this website when hovering over brand names — https://www.ahundredmonkeys.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Источник

.text()

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

Contents:

.text() Returns: String

Description: Get the combined text contents of each element in the set of matched elements, including their descendants.

version added: 1.0 .text()

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:

div class="demo-container">
div class="demo-box">Demonstration Box div>
ul>
li>list item 1 li>
li>list strong>item strong> 2 li>
ul>
div>

The code $( «div.demo-container» ).text() would produce the following result:

Demonstration Box list item 1 list item 2

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

As of jQuery 1.4, the .text() method returns the value of text and CDATA nodes as well as element nodes.

Example:

Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).

Источник

Читайте также:  Writing json files in java
Оцените статью