This question already has answers here:
How can I find elements by text content with jQuery?
(8 answers)
Closed 2 years ago.
I have two divs with the same class name as :
<button>Click to change font weight.</button>
<div class="wt">Paragraph 1</p>
<div class="wt">Paragraph 2</p>
Using jQuery, I'm trying to change the font-weight of the div that has "Paragraph 1" as text. What would be the best way to approach this? This is what I'm trying - but it would of course set both the divs' text to bold:
$("button").click(function(){
if($(".wt").text().trim() == "Paragraph 1")
{
$(".wt").css("font-weight","bold" )
}
});
});
You can use jQuery contains() method:
$(".wt:contains(Paragraph 1)").css("font-weight","bold" )
For your query, I would add class instead:
$('.wt:first').addClass('font-weight-bold');
If you're using bootstrap 4, it would automatically support the class. Otherwise, add this rule in your stylesheet:
.font-weight-bold {
font-weight: bold;
}
If your paragraph is not the first in the DOM Tree and looking for the text, then use contains selector as suggest in other answer:
$('.wt:contains("Paragraph 1")').addClass('font-weight-bold');
One last thing, I forgot about to mention that you can use toggleClass to toggle the changes upon button clicks.
$('.wt:first').toggleClass('font-weight-bold');
You can use jQuery's :contains() selector.
I've added some additional functionality so you can toggle between font-weight's. It is worth noting that calling .css('font-weight') with jQuery will not return you string values such as normal or bold; instead calling this will retrieve numbers ('400' === 'normal', '700' === 'bold' etc).
$("button").click(function() {
let par1 = $(".wt:contains('Paragraph 1')");
// Toggle between font-weights
par1.css(
'font-weight',
(['normal', '400'].indexOf(par1.css('font-weight')) === -1) ? 'normal' : 'bold'
);
// Or, uncomment and use this if you do not wish to toggle the div
// par1.css('font-weight', 'bold');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click to change font weight.</button>
<div class="wt">Paragraph 1</div>
<div class="wt">Paragraph 2</div>
Hope this helps,
$("button").click(function(){
$(".wt").each(function(){
if($(this).text() == "Paragraph 1")
$(this).css("font-weight","bold");
});
});
Related
This question already has answers here:
How do I check if string contains substring? [duplicate]
(12 answers)
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 11 months ago.
I am trying to hide a div if another div contains a specific word.
This is my HTML
<div class="dynamic">
This text is hidden if another div contains the word "download"
</div>
<div class="something">
<div class="btn-download">
If this text has the word "download" the div with class "dynmaic" is hidden
</div>
</div>
JS
jQuery(document).ready(function($){
if ( $('.btn-download').text() === 'download' ) {
$('.dynamic').hide();
}
});
What am I doing wrong? And do I need jQuery for it?
JSFiddle
many many thanks in advance
If a text in div contain a specific word you can use includes method on string ($(selector).text().includes('your-text-search'))
if ( $('.btn-download').text().includes('download') ) {
$('.dynamic').hide();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic">
This text is hidden if another div contains the word "download"
</div>
<div class="something">
<div class="btn-download">
If this text has the word "download" the div with class "dynmaic" is hidden
</div>
</div>
This can help, I'm not an expert but try to edit.
$(document).ready(function() {
$("#dynamic").click(function() {
var res = $('#dynamic').text();
if (res == "value") {
var hide = document.getElementById("something");
hide.style.display = "none";
}
});
});
Your example code needs jQuery. This is a solution using ECMAScript 5 or older and jQuery.
jQuery(document).ready(function($){
if ( $('.btn-download').text().indexOf('download') !== -1) {
$('.dynamic').hide();
}
});
Please check the fiddle https://jsfiddle.net/1sx39q6h/
For jQuery + ECMAScript 6, you have the solution of #jeremy-denis.
I have a project In which i want to select all the elements that have following classes: .GB1, .GB2, .GB3, .GB4, .GB5 and this will continue until .GB400.I also have other elements which contain the following types of classes .GB, .GBholder, .GB_color, .GB-size and I don't want to select this elements. I don't have any other element classes which starts with .GB and after .GB it have number like .GB1 or GB20. So I have a idea. But I don't know how to do this with jquery or javascript.The idea is "I Will tell the browser that, select all the elements that started with .GB and after .GB It have one or many numbers." Is it possible? How can I do it via js or jquery?
Here is the code I am trying now:
$('.color').on('click', function() {
$('*[class^="GB"]').css("background-color","red");
})
I have already wrote all the html and some long css by this classes. So It will take too many time change this class names.
You can use filter() and isNaN() method like following.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="GB1">GB1</div>
<div class="GB2">GB2</div>
<div class="GB3">GB2</div>
<div class="GBholder">GB holder</div>
<div class="GB_color">GB color</div>
<input type="button" value="Click" class="color"/>
<script>
$('.color').on('click', function () {
$('[class^="GB"]').filter(function () {
return isNaN($(this).attr('class').slice(2)) == false;
//if your elements has more than one class then add GB first and try this
//var cl = $(this).attr('class').split(' ')[0];
//return isNaN(cl.slice(2)) == false;
}).css("background-color", "red");
})
</script>
I have two event types on my page and I wanted to automatically add a CSS class to the <span> items in the parent class (div) of the event if their data-colr="value".
For instance:
if data-colr="#123456" of the class .eventon_list_event exists, add color="#e1e1e1" to the <span> inside that parent class .eventon_list_event.
Any help would be greatly appreciated!
HTML:
<div class="eventon_list_event" data-color="#123456">
Div
<span>Span</span>
<span>Span</span>
<span>Span</span>
<span>Span</span>
<span>Span</span>
</div>
CSS:
.span-color {
color: #f06;
}
jQuery:
if($('.eventon_list_event').data('color') === '#123456') {
$('.eventon_list_event').find('span').addClass('span-color');
}
Codepen
Use this:
$('.eventon_list_event').each(function(){
if ($(this).attr('data-colr') == '#123456') {
$('this').find('span').css('color', '#e1e1e1');
}
});
jQuery:
$(document).ready(){
if ($(".eventon_list_event").data("colr")=="#123456")
{
$(".eventon_list_event span").css("color", "#e1e1e1");
}
}
For multiple divs:
$(document).ready(){
$('.eventon_list_event').each(function(){
if ($(this).data("colr") == '#123456') {
$(this).find('span').css('color', '#e1e1e1');
}
});
}
Each - loops through all the instances of the DOM element
If you were to miss that, jquery would take data from the first div instead of all separately
Be sure to always write this instead of 'this'
This is the bad way to do it:
Bad Way
And this is the good way:
Good way
I have javascript code that tests if a div has some non whitespace text content.
This works but it cannot differentiate between text content or style tag declarations within the div and the test fails when there is no text content but a style tag with css data.
Question is how to test for empty text content while ignoring the style tag?
HTML:
<div id='test1'>
<div> </div>
</div>
<div id='test2'>
<div> </div>
<style>
.style1{
border:1px;
}
</style>
</div>
Javascript:
// Works
if($('#test1').text().trim().length==0){
alert('test1 has no content!');
}
// Does not work due to style1 declaration within style tag within div
if($('#test2').text().trim().length==0){
alert('test2 has no content!');
}
Test URL:
http://jsfiddle.net/sLDWB/
One option is cloning the element and removing the style tags:
$.fn.isTextless = function() {
var txt = this.first()
.clone()
.find('style')
.remove()
.end()
.text();
return $.trim(txt).length === 0;
}
if ( $('#test2').isTextless() ) {
alert('test2 has no content!');
}
http://jsfiddle.net/5Z3M4/
You can just use a common class for all the elements you need to check, loop through them using each, store the initial HTML, remove the style tag, do your check and restore the initial HTML. Like so :
$('.testdiv').each(function() {
var divHtml = $(this).html();
$(this).find('style').remove();
if($(this).text().trim().length==0){
alert( $(this).attr('id') + ' has no content!');
}
$(this).html(divHtml);
});
http://jsfiddle.net/sLDWB/1/
Subtract the style tag's length with the actual length.
Try,
if($('#test1').text().trim().length==0){
alert('test1 has no content!');
}
if($('#test2').text().trim().length - $('#test2 style').text().trim().length ==0){
alert('test2 has no content!');
}
DEMO
Use following javascript code
document.getElementById('test2').innerText
The style tag is meant to go in the head of a page. Why do you even have .style1 there if no element uses style1? If you want to change the style of a div, either do <div style="border: 1px;"> or make a style declaration in the <head> part of the HTML page.
In short, you shouldn't ever have a <style> tag outside of <head>.
I dont think I am using the .remove correctly because instead of "info about canada" being removed from the div "info", it is stacked on top of "info about russia" instead.
js
if (code == 'ca') {
$('#info').append('<p class="i">info about canada</p>');
} else if (code == 'ru') {
$('#info').remove('.i');
$('#info').append('<p class="i">info about russia</p>');
}
html
<div id="info">
<h3>Info</h3>
</div>
If you are trying to replace the contents of #info then don't use remove, empty, or append, just use html:
$('#info').html('<p class="i">info about russia</p>');
I figured it out...I used .empty instead.
Their is no need to pass parameters to remove..
Just do:
$('#info .i').remove();
and it will remove the .i from the $('#info') div