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.
Related
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");
});
});
This question already has answers here:
Using .text() to retrieve only text not nested in child tags
(30 answers)
Closed 3 years ago.
Is there any way in CSS or jQuery to select only the plain texts inside of an element?
I have an HTML code like this:
<div class="container">
"some text 1"
<div> ... </div>
<img src="#">
"some text 2"
<div> ... </div>
</div>
and want to select only the texts that are directly inside the container element.
I have searched on the internet and found some solutions like using first-child(), nth-child(), last-child() but since the texts are not always in the specific positions; using the *-child() selectors don't solve my problem.
The :nth-child() pseudo-class selector only works with Elements, not with Text Nodes.
In order to do that get the parent node, then get child node collection using childNodes property and finally, you can access TextNode by using index. To remove you can use remove() method or use removeChild() method on parent element.
// get parent elemeent
let cont = document.querySelector('.container');
// get child node collection which is a live collection
let nodeCollection = cont.childNodes;
// get first child
let text1 = nodeCollection[0].textContent;
// get next child(index is 4 since there is an empty text node in between div and img)
let text2 = nodeCollection[4].textContent;
// remove the last element first since nodeCollection is live
// collection removing an element will update the index
nodeCollection[4].remove();
nodeCollection[0].remove();
console.log(text1, text2)
<div class="container">
"some text 1"
<div> ... </div>
<img src="#"> "some text 2"
<div> ... </div>
</div>
<div id="myDiv">
text 1
<div>div text</div>
text 2
<span>span text</span>
</div>
<script>
$(document).ready(function() {
var $myDiv = $('#myDiv');
var texts = [];
for(var i = $myDiv[0].childNodes.length - 1; i >= 0; i--) {// Starting from last to first, so we can remove from array without breaking JS
if($myDiv[0].childNodes[i].nodeType == Node.TEXT_NODE) {// Is text only?
texts.push($myDiv[0].childNodes[i].nodeValue);// Add this text to array
$myDiv[0].removeChild($myDiv[0].childNodes[i]);// Remove from HTML
}
}
texts = texts.reverse();
//texts = ["text 1", "text 2"]
});
</script>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm a bit new to javascript and jquery, and I have some troubles doing what I want in a "nice" way.
I have a HTML web page like this:
<div class="list-group">
All
Foo
Bar
FooBar
</div>
<div class="row">
<div class="category-0">element 1</div>
<div class="category-1">element 1</div>
<div class="category-1">element 1</div>
<div class="category-0">element 1</div>
<div class="category-2">element 1</div>
<div class="category-0">element 1</div>
<div class="category-2">element 1</div>
</div>
I would like to add some kind of "filter", where if you click on a certain category link, all elements from other categories will disappear.
I managed to do it by adding a class to my css called invis with "display:none", and then wrote this:
$( ".list-group-item" ).click(function() {
$(".list-group-item").removeClass('active');
$( this ).toggleClass("active");
var test = "." + event.target.id;
$(".category-0").addClass('invis');
$(".category-1").addClass('invis');
$(".category-2").addClass('invis');
if (test == ".category-0")
$(".category-0").removeClass('invis');
if (test == ".category-1")
$(".category-1").removeClass('invis');
if (test == ".category-2")
$(".category-2").removeClass('invis');
if (test == ".category-all") {
$(".category-0").removeClass('invis');
$(".category-1").removeClass('invis');
$(".category-2").removeClass('invis');
}
});
This does the job, but I'd like to find a "cleaner" way of doing it. How can I improve it?
Thanks !
One way to do it using jQuery would be to hide all of the <div>s when a filter control is clicked, then unhide the specific ones that you want to show.
This way you won't need your extra invis class.
you will notice the "^=" symbol in the below code it simply is a selector that literally means "starts with".
$('a[id^="category"]').click(function() {
// when an <a> element is click THAT has an ID that starts with "category" ...
$('div[class^="category"]').hide();
// hide every <div> that's ID starts with "category" ...
$('div.' + this.id).show();
// re-show every <div> that's CLASS matches the original <a>'s ID ...
});
$('a[id="show-all"]').click(function() {
// if the "all" is clicked, show them ALL again.
$('div[class^="category"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group">
All
Foo
Bar
FooBar
</div>
<div class="row">
<div class="category-0">Foo</div>
<div class="category-1">Bar</div>
<div class="category-1">Bar</div>
<div class="category-0">Foo</div>
<div class="category-2">FooBar</div>
<div class="category-0">Foo</div>
<div class="category-2">FooBar</div>
</div>
Hide all elements with class "row" and then un-hide all elements with class [id of what was clicked] within class "row".
$('.list-group-item').click(function(event) {
$('.row').addClass('invis');
$('.row.' + event.target.id).removeClass('invis');
});
By simply adding to all your categories the .category-all you've done half-job.
Now you can control the id>>>class relations much easily.
jsBin demo
If you need to always have at least one category visible it's quite simple:
var $btns = $(".list-group-item");
var $ctgs = $("[class^='category-']");
$ctgs.addClass("category-all"); // Job done! :D :D
$btns.click(function(e) {
$ctgs.hide(); // Hide all
$("."+this.id).show(); // Show realated
});
Otherwise, The code below will allow you to have any combination you desire
And even hide/toggle the active ones:
jsBin demo
var $btns = $(".list-group-item");
var $ctgs = $("[class^='category-']");
$ctgs.addClass("category-all"); // Job done! :D :D
$btns.click(function(e) {
$ctgs.not("."+this.id).hide(); // Hide all (not this...)
$("."+this.id).toggle( $(this).hasClass("active") ); // Toggle realated
});
Disclaimer: not tested.
$('.list-group-item').click(function() {
$('.list-group-item').removeClass('active');
$(this).addClass('active');
var id = $(this).attr('id');
if(id == 'category-all') {
$('div.row > div').show();
} else {
$('div.row > div.' + id).show();
$('div.row > div:not(.' + id + ')').hide();
}
});
Here's another version. Added color coding for visibility.
*Edit updated to actually have the right behavior.
http://codepen.io/anon/pen/NPrGJp
$( ".list-group-item" ).click(function() {
$('.active').removeClass('active');
$(this).addClass('active');
$('.row > div').show();
$('.' + $(this).attr('id')).hide();
});
This question already has answers here:
Get only visible text with jquery
(3 answers)
Closed 8 years ago.
I try to get content inside element and i want that is the same when it shown on browser
Example
<pre class="yyy">Hello this is <span style="display: none;"> test </span> text </pre>
and
// how to alert (get) content like when it shown on browser: Hello this is text
alert($(".yyy").html());
I want alert result is: Hello this is text the same when it shown on browser. Is that possible? how to do that thank.
Here is my code
I would do this :
alert($(".yyy").clone().find(':not(:visible)').remove().end().text());
Demonstration
I think this is what you are looking for.
jQuery.fn.visibleText = function() {
return $.map(this.contents(), function(el) {
if (el.nodeType === 3) {
return $(el).text();
}
if ($(el).is(':visible')) {
return $(el).visibleText();
}
}).join('');
};
alert($(".yyy").visibleText());
Here is a fiddle.
This question already has answers here:
JQuery change inner text but preserve html
(14 answers)
Closed 9 years ago.
How can I change html inside a Div in HTML without affecting inner divs inside the parent div in Jquery.
So far I have this:
HTML:
<div id="div_to_change">
This is the text
<br>
to be changed
<div id="div_that_shouldnt_change">
text that should not change
</div>
<div id="div_that_shouldnt_change2">
text that should not change
</div>
</div>
JQUERY:
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("changed text");
The only problem is that it works fine if there are no tags on the html, but for example it doesn't change after the <br> or <strong> etc.
JSFIDDLE HERE
One way:
$('#div_to_change').contents().each(function () {
//select only nodes with type 3 and having a node value to ignore empty lines, format chars etc
if(this.nodeType == 3
&& $.trim(this.nodeValue)
)
{
$(this).replaceWith("changed text")
}
});
Demo
Or Just with the filter:
$('#div_to_change').contents().filter(function () {
return (this.nodeType == 3
&& $.trim(this.nodeValue)
)
}).replaceWith("changed text");
Demo