appending and removing content with jquery - javascript

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

Related

jQuery - change font-weight of specific text with same class name [duplicate]

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");
});
});

Jquery - if element contains a class, add HTML after element

I've got a booking form.booking-wrap with 2 elements in it, div#booking and then div.quantity
<form class="booking-wrap">
<div id="booking"></div>
/* insert div#message IF div.quantity is present inside div.booking-wrap */
<div class="quantity"></div>
</form>
The div.quantity is only present dynamically for some bookings.
What I am trying to achieve is that if the div.quantity is present, then I would like to insert an additional html div#message, but this new div should appear after div#booking and before div.quantity
I am trying the following jQuery:
if($('.booking-wrap:has(div.quantity)')){
$('#booking' ) .after( '<div id="message">Message</div>');
}
But that doesn't seem to work.
I then tried this:
$('.booking-wrap:has(div.quantity)').append($('<div id="message">Message</div>'));
This works and the new div appears, however it is just next to the quantity div.
How can I get it to show after the #booking , but before .quantity?
Any selector returns an object, you should check the length property of the returned object. Like $('.booking-wrap:has(div.quantity)').length
Though, I prefer $('.booking-wrap > div.quantity').length
if($('.booking-wrap > div.quantity').length){
$('#booking').after('<div id="message">Message</div>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="booking-wrap">
<div id="booking">booking</div>
<div class="quantity">quantity</div>
</form>
Try using prepend instead of append, since the selector $('.booking-wrap:has(div.quantity) will return the (div.quantity) element.
Example:
$('.booking-wrap:has(div.quantity)').prepend($('<div id="message">Message</div>'));
You can use "hasClass()" jQuery function to check class is exist or not:
Try This
if($( ".booking-wrap" ).children('div').hasClass( "quantity" )){
jQuery('<div id="message">Message</div>').insertAfter('.booking');
}
Try This jQuery.
if($(".quantity").length ){
$('#booking' ).after( '<div id="message">Message</div>');
}
You need to put the div you are adding within a function.
if($('.booking-wrap:has(div.quantity)')){
$( "#booking" ).after(function() {
return '<div id="message">Message</div>';
});
}

jQuery select the function selector

I'm trying to achieve something inside a function, to actually access the parent selector.
Here is a small snippet of my HTML code:
<div class="module-row module-tab pull-right" id="modtab-sql_net">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-1">
</div>
<div class="module-row module-tab pull-right" id="modtab-sql_dss">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-2">
</div>
Here is the jQuery script I tried:
$('div[id^="modtab-"]').click(function(){
$(this).next('div[id^="tab-module-row"]').toggle(function(){
$(this).next('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
// The above line is incorrect. I need to change img attr for the class which is inside the div being clicked
});
});
Now, I want to actually change the image icon from a "plus" to a "minus" (the filenames are kept such).
I need to change $(this).next('.modtab-toggle') in the code to something that can work.
Please do NOT suggest to simply access the class using $('.modtab-toggle') as I have multiple such div tags in the code. It won't work out that way.
Thanks for any help.
Try this:
$('div[id^="modtab-"]').click(function(){
$(this).find('.modtab-toggle').attr("src", function(i, attr){
var o = this.src.indexOf('plus') > -1 ? this.src.replace('plus', 'minus') : this.src.replace('minus', 'plus');
return o;
});
});
See the Demo # Fiddle
try something like this
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('.tab-module-row').toggle(function(){
$this.find('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
});
});
Note: you should use class instead of id because it should be unique
#tab-module-row ->.tab-module-row
EDITED ANSWER
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('div[id^="tab-module-row"]').toggle(function(){
var img = $this.find('.modtab-toggle'); // your image object
// your condition to check which image to display will goes here.
});
});
change $(this).next('.modtab-toggle') to $(this).find('.modtab-toggle') to make it work.
See find() docs here

jQuery get text in element but ignore style tags

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>.

How do you use jQuery to find an element by its html?

I am trying to find a way to use jQuery to get the first empty div with a certain class. I tried this:
$(".box[html='']").
but it didn't work. Is there an easy way to do this?
That syntax only works for attributes. For HTML contents, you can use .filter():
$('.box').filter(function () {
return $.trim($(this).html()) === '';
}).eq(0);
Edit: The problem with :empty is that line-breaks and spaces are not empty. So:
<div> </div>
<div>
</div>
... won't match.
This should work:
$('.box:empty:first')
http://api.jquery.com/empty-selector/
How about this:
You html:
<div class="empty"></div>
<div class="empty"></div>
your script:
$(document).ready(function(){
$(".empty:empty:first").html("JJJJ");
});
Check this
http://jsfiddle.net/y4Ef2/
var boxEq;
$('div.box').each(function(i,obj){
if (boxEq === void(0)) {
if ($(obj).html() === '') {
boxEq = i;
break;
}
}
});
// this is your div
$('div.box').eq(boxEq);
Try this one:
$('.box').each(function(){
if($(this).text().length == 0)
//box is empty
});
$("div.box:empty").eq(0)
added .eq(0) since you said first empty

Categories