Changing text after a span - javascript

Is it possible in jquery to insert text after a span. For example, I would like to change the price value after the dollar sign below.
<div id="price">
<span>$</span>
10.00
</div>
The only way I can see how to do this, is to remove the span element (store as variable), add the price value, and then append the currency value again. Seems pretty hacky.

You can change the price using lastChild and nodeValue like following.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>
<script>
var price = $('#price')[0];
price.lastChild.nodeValue = "155.00";
</script>

Yes you can do it as:
$("#price").contents(":not(span)").text("Text");

Just add another span to wrap around the price value.
<div id="price">
<span>$</span>
<span id="price-value">10.00</span>
</div>
Then you can $("#price-value") to manipulate that part on its own.

One another way
<script src="http://code.jquery.com/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>
<script type="text/javascript">
$('#price').contents().last()[0].textContent=' 20.00';
</script>

As a much easier alternative, one might also use CSS to prepend the currency symbol. This avoids using the span altogether and allows changing the currency symbol.
CSS Examples:
.currency div::before { content: "$" }
.currency.yen div::before { content: "¥" }
And a working code snippet:
$('#item1').html('10.00');
$('#item2').html('8.80');
$('#item3').html( '20.30');
.currency.dollar div::before { content: "$" }
.currency.pound div::before { content: "£" }
.currency {
font-family: monospace;
font-size: 24px;
font-weight: bold;
border: 1px lightgray solid;
width: 8em;
padding: 4px;
text-align: right;
background-color: ghostwhite;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="currency dollar">
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
</div>

try this
$("#pri").text("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price">
<span id='si'>$</span>
<span id='pri'>10.00</span>
</div>

Setting the text need some old fashioned JavaScript assistance. Using textContent.
$('#price').contents().filter(function() {
return this.nodeType == 3;
}).last()[0].textContent = 'changed';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>

You can try insertAfter() in jQuery.
HTML:
<button>Insert span element after span element</button>
<br>
<div id="price">
<span>$</span>
</div>
jQuery:
$(document).ready(function(){
$("button").click(function(){
$("<span>100</span>").insertAfter("span");
});
});

Related

How do I toggle the background colors within a list of divs?

From a list of items, each in separate divs, the user can select and click only one. The background color should change on the selected one. If the user changes their mind, they can select another one, and the background color should change to the selected color and all the other divs on the list should change back to the default background color.
It's basically the same logic as a radio button on a form. Only one can be selected at a time.
How do I achieve this?
I have attempted to use the element.classList.toggle property. But it only handles each individually. Are there a javascript command(s) to handle this?
<style>
.teamSelected{
background-color: red;
border-radius: 4px;
}
</style>
<div onclick="toggleBackground(team1)">
<div id="team1">
</div>
</div>
<div onclick="toggleBackground(team2)">
<div id="team2">
</div>
</div>
<div onclick="toggleBackground(team3)">
<div id="team3">
</div>
</div>
<script>
function toggleBackground(teamnumber) {
var element = document.getElementById(teamnumber);
if (element) {
element.classList.toggle("teamSelected");
}
}
</script>
Thanks!
You are passing variables to the function, which don't exist. You need to put them in quotes, because the function is expecting strings.
const allDivs = document.querySelectorAll('.div');
function toggleBackground(teamnumber) {
var element = document.getElementById(teamnumber);
if (element) {
allDivs.forEach(function(el){
el.classList.remove('teamSelected');
});
element.classList.add("teamSelected");
}
}
.toggle > div {
width: 100px;
height: 100px;
border: 1px solid #000;
}
.teamSelected {
background-color: red;
border-radius: 4px;
}
<div onclick="toggleBackground('team1')" class="toggle">
<div id="team1" class="div">
</div>
</div>
<div onclick="toggleBackground('team2')" class="toggle">
<div id="team2" class="div">
</div>
</div>
<div onclick="toggleBackground('team3')" class="toggle">
<div id="team3" class="div">
</div>
</div>
seems like this is something you want?
let x = ('.something');
$(x).on('click', function(){
$(x).css('background','blue');
$(this).css('background', 'green');
});
.something{
width: 100px;
height: 100px;
background: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="something">
<div id="team1">
</div>
</div>
<div class="something">
<div id="team2">
</div>
</div>
<div class="something">
<div id="team3">
</div>
</div>

How to use toggleClass on multiple elements but not at the same time

so the problem I have is quite simple.
I have a span <span class=""spDetails>Show More</span> and with this element I am expanding a section to show more text.
The problem I have is that I want to use this function in other sections of the page.
This is the jquery code which I am using to toggleClass active.
$(".spDetails").click(function() {
$(".divFees").toggleClass("feesActive");
});
My question is: I don't want to write this line of code for every element using this toggle, is there a way to create this for multiple elements with different class names or IDs? Thanks.
Right, so here is my HTML: (shortened version!)
<div id="optionOne" class="elementOne">
<div class="divFees">
<p>Text Text</p>
</div>
<span class="showMore">Show More</span>
</div>
<div id="optionTwo" class="elementTwo">
<div class="divFees">
<p>Text Text</p>
</div>
<span class="showMore">Show More</span>
</div>
I m trying to hide and display <div class="divFees"></div> only when there child <span> is clicked.
You can just append your desired elements in the selector using ,.
$(".divFees , .otherOnes , #otherOneWithId").toggleClass("feesActive");
If the toggleable section comes after the toggling span :
$(".spDetails").on("click", function(e) {
$(this).next().toggleClass("active");
});
[id*='div'] {
height: 60px;
background: #f2f2f2;
border: #f6f6f6;
}
.active {
background: #555555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="spDetails" data-toggle="#div1">Toggle 1</span>
<div id="div1"></div>
<span class="spDetails" data-toggle="#div2">Toggle 2</span>
<div id="div2"></div>
</section>
Or with extra attributes to specify the target:
$(".spDetails").on("click", function(e) {
var target = $($(this).data("toggle"));
target.toggleClass("active");
});
[id*='div'] {
height: 60px;
background: #f2f2f2;
border: #f6f6f6;
}
.active {
background: #555555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="spDetails" data-toggle="#div1">Toggle 1</span>
<div id="div1"></div>
<span class="spDetails" data-toggle="#div2">Toggle 2</span>
<div id="div2"></div>
</section>
I imagine two ways:
Easy way:
Make function with args for your event. Example:
function setToogleClass(button, toggleElement, toggleClass) {
$('.' + button).click(function() {
$('.' + toggleElement).toggleClass(toggleClass);
});
}
setToggleClass("spDetails", "divFees", "feesActive")
Hard way:
Set event function by all classes who has className and who found child or parent or current elements.
function initToggleEvents() {
var toggleButtons = $('toggle-button');
var activeClassName = 'toggle-active';
toggleButtons.forEach(function(toggleButton) {
toggleButton.click(function(event) {
// if event.target has parentNode that toggleClass(activeClassName)
// else another rules
}
}
}

Hide div if text string length is more than 3 characters

I have one div placed over the other and I want it to disappear if the text inside it is longer than 3 characters. I have tried to do this with the code below but it doesn't seem to work. Any advice would be much appreciated.
$(document).ready(function() {
if ($(#top).text().length > 3) {
$(this).addClass('hide')
$(this) removeClass('show');
}
});
.show {
visibility: visible;
}
.hide {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTml:
<div id="bottom" class="hide" Style="background-color: green; width:398px; height:196px;">
<div id="top" class="show" Style="background-color: blue; width:398px; height:196px;">
<!-- PHP REQUEST THAT GIVES LATEST UPDATE GOES HERE. If text string is longer than 2 characters I want this to hide. -->textmorethan3characters
</div>
</div>
There are syntax errors in your code.
$(#top) needed to be replaced by $("#top") (see the quotes around).
There was a missing . before removeClass function.
Correcting the above, the major problem with your code was wrong use of $(this). You thought that it would point to #top, but it didn't.
Correcting all of these, below is a working example:
$(document).ready(function() {
if ($("#top").text().length > 3) {
$("#top").removeClass('show').addClass('hide');
}
});
.show {
visibility: visible;
}
.hide {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTml:
<div id="bottom" class="hide" Style="background-color: green; width:398px; height:196px;">
<div id="top" class="show" Style="background-color: blue; width:398px; height:196px;">
<!-- PHP REQUEST THAT GIVES LATEST UPDATE GOES HERE. If text string is longer than 2 characters I want this to hide. -->textmorethan3characters
</div>
</div>
$(document).ready(function() {
if ($("#top").text().length > 3)
$("#top").fadeOut(2000);
else
$("#top").fadeIn(2000);
});
#top,#bottom{
width:398px;
height:196px;
color:#fff;
}
#top{background-color: blue;}
#bottom{background-color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bottom">
<div id="top">sdadsdsad</div>
</div>

Change Elements HTML but Ignore Last Child

With the way I have my HTML marked up....
<textarea></textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
Is it possible to change the html inside of .body without changing the html inside of .content?
EDIT:
I'm working on my code editor and my <script> tag in this case is replaced with .content, and <body> tag is replaced with .body.
The .before API seems to be the best solution for my case except if only 3 characters are added (ex. lol). The result in .body is (ex. lolollol)
$('textarea').keyup(function() {
$('.content').before(this.value)
return false
}).trigger('keyup')
textarea {
width: 98%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
This is tricky, because .body may contain text nodes.
jQuery's contents() method helps :
$('textarea').keyup(function() {
$('.body')
.contents() //get both text nodes and element nodes
.each(function() {
if(this.className !== 'content') {
this.nodeValue= this.innerHTML= ''; //nodeValue needed for text nodes,
//innerHTML for element nodes
}
});
$('.content').before(this.value);
}).trigger('keyup');
textarea {
width: 98%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<ol>
<li>test data here</li>
</ol>
</textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
One workaround would be to get the reference to the .content element and append() it back in to the .body element after re-setting the html(). Try this:
$("textarea").keyup(function() {
var $content = $('.content');
$(".body").html(this.value).append($content);
}).trigger("keyup")
textarea {
width: 98%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
you can append into $contentrather than changing the entire html
$('textarea').keyup(function(){
$('.body').html(this.value).append($content)
}).trigger('keyup');
fiddle : https://jsfiddle.net/atg5m6ym/3320/
Keep HTML, CSS, and JS separate. See Snippet.
SNIPPET
$(".html").keyup(function() {
$(".body").html(this.value)
}).trigger("keyup")
$(".css").keyup(function() {
$(".style").html(this.value)
}).trigger("keyup")
$(".js").keyup(function() {
$(".script").html(this.value)
}).trigger("keyup")
textarea {
width: 98%;
height: 100px;
}
.tag {
font: 700 16px/1.45 'Consolas';
color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>HTML</legend>
<textarea class="edit html">
</textarea>
</fieldset>
<fieldset>
<legend>CSS</legend>
<textarea class="edit css">
</textarea>
</fieldset>
<fieldset>
<legend>JavaScript</legend>
<textarea class="edit js">
</textarea>
</fieldset>
<hr/>
<section class="printer">
<div class="tag"><html></div>
<div class="tag"><head></div>
<div class="tag"><style></div>
<div class="print style">
</div>
<div class="tag"></style></div>
<div class="tag"></head></div>
<div class="tag"><body></div>
<div class="print body">
</div>
<div class="tag"><script></div>
<div class="print script">
</div>
<div class="tag"></script></div>
<div class="tag"></body></div>
<div class="tag"></html></div>
</section>

minimize maximize the div ? javascript or jquery which works for all the div

i want to give minimize and maximize facility to my div..for that i have written following code in my jsp page
<div id="widnow" style="width: auto;">
<div id="title_bar">
<button type="button" class="max" id="button">
<img id="max" src="<%=request.getContextPath()%>/img/Minimize.png" />
</button>
</div>
<div id="box" style="height:auto; width: auto;">
<span id="info3" style="display: none;"></span>
<div id="chart3" style="width:80%; height:300px;"></div>
</div>
</div>
following is my css
#widnow{
width:400px;
border: 1px solid #DCDCDC;
}
#button{
width: 25px;
height: 24px;
float:right;
cursor:pointer;
position:relative;
margin: 0px 0px 0px 0px;
}
#title_bar{
background-image: url("<%=request.getContextPath()%>/img/Header Background.png");
height: 25px;
width: auto;
border-bottom: 1px solid #DCDCDC;
}
following is my js
$("#button").click(function(){
var isclass = $(this).attr('class');
if (isclass == "max")
{
$("#max").attr("src","<%=request.getContextPath()%>/img/Minimize.png");
$(this).removeClass('max');
}
else{
$(this).addClass('max');
$("#max").attr("src","<%=request.getContextPath()%>/img/Maximize.png");
}
$("#box").slideToggle();
});
Its Working Well When there is one div i want to give this facility..but with one single java script function or with j-query how can i achieve this?i have many div in single page and all should have there individual maximize and minimize facility.so can anyone tell me how can change my java script that works with all div?
Reconstructing your code a bit:
function activateMaxMin(elemButton,elemMax,elemBox)
{
var isclass = elemButton.attr('class');
if (isclass == "max")
{
elemMax.attr("src","<%=request.getContextPath()%>/img/Minimize.png");
elemButton.removeClass('max');
}
else{
elemButton.addClass('max');
elemMax.attr("src","<%=request.getContextPath()%>/img/Maximize.png");
}
elemBox.slideToggle();
}
$("#button").click(function(){
activateMaxMin($(this),$("#max"),$("#box"));
});
In case there is another button like this, use:
$("#button1").click(function(){
activateMaxMin($(this),$("#max1"),$("#box1"));
});
Of course, it could have been done in more efficient way, but that would need rewriting your code entirely.
<div id="widnow" class='window' style="width: auto;">
<div id="title_bar" class='title_bar'>
<button type="button" class="maxMinButton" id="button">
<img id="max" src="<%=request.getContextPath()%>/img/Minimize.png" class='max'/>
</button>
</div>
<div id="box" style="height:auto; width: auto;" class='box'>
<span id="info3" style="display: none;"></span>
<div id="chart3" style="width:80%; height:300px;"></div>
</div>
</div>
//javascript function
function activateMaxMin(elemButton,elemMax,elemBox)
{
var isclass = elemButton.attr('class');
if (isclass == "max")
{
elemMax.attr("src","<%=request.getContextPath()%>/img/Minimize.png");
elemButton.removeClass('max');
}
else{
elemButton.addClass('max');
elemMax.attr("src","<%=request.getContextPath()%>/img/Maximize.png");
}
elemBox.slideToggle();
}
$(document).ready(function(){
$(".maxMinButton").click(function(){
var elemButton=$(this);
var maxMinWidnow=button.closes('.window');
var elemMax=$(".max:firs",maxMinWidnow);
var elemBox=$(".box:first",maxMinWidnow);
activateMaxMin(elemButton,elemMax,elemBox)
});
});
This is the best I could get without doing lots of modifications to your code. Notice the added classes in each div in html, that are necessary. Be careful during modification.
Just change id notation "#" to class selector "." like #max to .max
What browser does it would work only for first occurrence of the id and try to change the img id to class
Well in your case that is different i have created a fiddle see at that if that helps you:
http://jsfiddle.net/32e2V/
$(".button").click(function () {
$(this).closest('div').siblings(".box").slideToggle();
if ($(this).text() == "max") {
$(this).text('min');
} else {
$(this).text('max');
}
});

Categories

Resources