Replacing all selected elements with javascript - javascript

I'm trying to select all spans with class .normal on my site, cut the first character and add € as the last character. I'm trying really hard but it just doesn't work even when I try to just replace that with "abc" or any string.
My javascript looks like that:
$(document).ready(function(){
var prices = document.querySelectorAll('span.normal');
for (i=0; i<prices.length; i++) {
prices[i].textContent = prices[i].substring(1) + "€";
}
}
});

Since you are using jQuery already how about making it completely in jQuery?
$(document).ready(function() {
$('span.normal').each(function() {
$(this).text($(this).text().substring(1) + '€');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>abc</span>
<span class="normal">abc</span>
<span>abc</span>
<span class="normal">abc</span>

var prices = document.querySelectorAll('span.normal');
for (var i = 0; i < prices.length; i++) {
prices[i].innerHTML = prices[i].innerHTML.substring(1) + "€";
}
.normal{
font-color:black;
}
<span class=normal >3543</span>
<span class=normal >34534</span>

Related

Split multiple class with same name using loop

I have a multiple tag in my webpage with the same class called price. Each tag is of that form
<p class="price">Price: 45$</p>
<p class="price">Price: 32$</p>
What I need at the end is to separate the price text in a span and the price in another so that it will be like that
<p class="price"><span class='h1'>Price:</span> <span class="h2">45$</span></p>
This is what I do until now but problem is that the span is not a tag but is insert as a simple string
let price = $(".price");
for (let i = 0; i < price.length; i++) {
let priceTitle = price[i].innerText.split(":")[0];
let priceToPay = price[i].innerText.split(":")[1];
price[i].innerText = ''; //Delete content of price
$(".price")[i].append("<span class='h1'>"+ priceTitle+"</span> <span class='h2'>"+ priceToPay +"</span>");
}
}
Can you help me fix this issue and perhaps optimize the code I already do.
You've just a few syntax errors e.g. you've set priceToPay then used price_toPay in your final line of code. Also jQuery.append() method is setting your content as textContent and not HTML but just use innerHTML instead. I've added a button for you to click so you can see the before and after effects. See below
window.onload = () => {
document.getElementById('mybutton').addEventListener('click', doFormat);
}
function doFormat() {
let price = $(".price");
for (let i = 0; i < price.length; i++) {
const priceTextContentArray = price[i].innerText.split(":");
let priceTitle = priceTextContentArray[0];
let priceToPay = priceTextContentArray[1];
price[i].innerHTML =
"<span class='h1'>" +
priceTitle +
"</span> <span class='h2'>" +
priceToPay +
"</span>";
}
}
.h1 {
background-color: skyblue;
}
.h2 {
background-color: coral;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
<button id='mybutton'>Format</button><br>
<p class="price">Price: 45$</p>
<p class="price">Price: 32$</p>
If you want to do it "the jQuery way", to build elements from strings you must use the $ constructor:
replace:
price[i].innerText = ''; //Delete content of price
$(".price")[i].append("<span class='h1'>"+ priceTitle+"</span> <span class='h2'>"+ priceToPay +"</span>");
by:
$(price[i]).html('').append( $("<span class='h1'>"+ priceTitle +"</span> <span class='h2'>"+ priceToPay +"</span>") );
As you see in jQuery you can also chain the calls, and use the .html() or .text() dedicated functions. html is more suitable here as you want to delete all inside your element, not just the text part
Notice that I also corrected your $(".price")[i] to $(price[i]), it is safer to use the var you loop on instead of doing a new jQuery selection and assume it will have the same index as in your loop

How to use multiple IDs in one function

How to use it on multiple ids such that when #more1 is clicked , #details1 will appear. And when #more2 is clicked , #details2 will appear?
Note that I want it only using one function.
Thank U.
$(document).ready(function () {
$('#more1,#more2').click(function () {
$('#details1,#details2').slideToggle();
});
});
You can use a more general selector: $('[id^="more"]').
This will select all items that have an id that starts with "more", and will have a click event tied to them.
Then you can use the number in the id property and use it to build the id of the target.
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
$(document).ready(function()
{
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="more1">One</button>
<span id="details1">Each Section</span>
</div>
<div>
<button id="more2">Two</button>
<span id="details2">Is Independent</span>
</div>
<div>...</div>
<div>
<button id="more25">Twenty Five</button>
<span id="details25">Of all the others</span>
</div>
You can check the id of the current item and act accordingly:
if($(this).attr('id') == 'more1') $('#details1').slideToggle();
A more elegant solution would be:
$('#details' + $(this).attr('id')[$(this).attr('id').length - 1]).slideToggle();
The last one uses the fact that the numbering in the ids is similar, and if you have less than 10 such ids it will work properly.
You can use for loop
$(document).ready(function()
{
var length = 9; // any number you need
for (var i = 0; i < length; i++ ) {
$('#more' + i).click(function()
{
$('#details' + i).slideToggle();
});
}
});

Creating step numbers dynamically in jquery

I hate manually typing steps numbers. So I was trying to write a small function to find some text and replace it with generated step numbers.
And I can't use the ol/li tags because I have multiple groups on the page. So I need to add an "a", "b", etc after the number.
My HTML:
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
This is my jquery (but it doesn't replace the ---- to a step number).
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
$(this).find(":contains('----')").each(function(){
$(this).text("("+counter+val+") ");
counter++;
});
});
});
So eventually, I want the webpage to finish like this:
(1a) My first step
(2a) This is another
(3a) And another
(1b) second group
(2b) second group 2
For each of the groupings, get the inner html and split it by newline
If it starts with '----', replace it with an incrementing line number, and append the v value.
Put the html back into the grouping.
$('.grouping').each(function(index, grouping){
var lines = grouping.innerHTML.trim().split("\n");
var lineNumber = 0;
var v = grouping.getAttribute('v');
lines.forEach(function(line, index){
if (line.startsWith('----')) {
lines[index] = '('+ (++lineNumber) + v +') '+ line.slice(4);
}
});
grouping.innerHTML = lines.join('\n');
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
I should not have a line number.
----And another
</span>
<br/>
<span class="grouping" v="b">
I also should not have a line number.
----second group
----second group 2
</span>
You can use split to split the text at '----' and concat with the values (added brs for lisibility so I used html instead of text):
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var arr = $(this).html().split('----');
if(arr.length > 1){
var str = arr[0], i, l = arr.length;
for(i = 1; i < l; i++){
str += '(' + i + val + ') ' + arr[i];
}
$(this).html(str);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step<br>
----This is another<br>
----And another<br>
</span>
<br/>
<span class="grouping" v="b">
----second group<br>
----second group 2<br>
</span>
.find() will not work. You should get text of the element and split() it and then change it using map() and replace() and reset text()
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
let lines = $(this).text().split('\n');
lines = lines.map(ln => {
if(ln.includes('----')){
ln = ln.replace('----',`(${counter}${val})`)
counter++;
}
return ln;
})
lines = lines.filter(ln => ln !== '');
$(this).text(lines.join('\n'));
});
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
First, I suggest wraping those groups into some kind of tag. for example, span:
<span class="grouping" v="a">
<span class="grouping-item">My first step</span>
</span>
And so on, it will be easier and faster to target those elements.
Then create one function to search through those new tags
$(function(){
// This will create those numbers
function createNumbers(el) {
const mainGroup = el.attr("v");
const children = el.children(".grouping-item");
let i = 1;
children.each(function(){
const currentText = $(this).text();
$(this).text( '('+i+mainGroup+')' + currentText );
i++;
});
}
$(".grouping").each(function(){
createNumbers($(this));
});
});

How to replace a text with coloured text using javascript

I am having this text in text area.
{color:#c91d1d}Hello{color}
when it is submitted, i want the text between {} tags to be shown in color specified inside {} tag with color:
how can i do so in javascript
use javascript built in function to extract color code
var colorValue = str.substring(7, 7);
it extract 7 characters from 7th position.
now change the color using:
document.getElementById("myH2").style.color = colorValue;
I hope this will work
You can use a regex like
$('#input').on('input', function() {
$('#result').html(this.value.replace(/\{color:(.*?)\}(.*?)((\{color\})|$)/g, '<span style="color:$1">$2</span>'));
}).triggerHandler('input');
textarea {
width: 100%;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="input">{color:#c91d1d}Hello{color} - {color:green}hi{color}</textarea>
<div id="result"></div>
Arun is right, and if you just need to get "Hello" from "{color:#c91d1d}Hello{color}" string you can do it like this
var justtext="{color:#c91d1d}Hello{color}".match(/\{.*\}(.*)\{.*\}/)[1];
For full replacement of text in textarea here's the code. Suppose textarea has id attribute "textarea1", change it with your id.
var textwithcolor =$("#textarea1").text();
var justtext=textwithcolor.match(/\{.*\}(.*)\{.*\}/)[1];
$("#textarea1").text(justtext);
this is how it can be done
No need to use regular expressions.
try this
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("{color}") > -1) {
newstr = newstr.replace("{color}", "</div>");
}
while (newstr.indexOf("{color:") > -1) {
newstr = newstr.replace("{color:", "<div style='color:");
newstr = newstr.replace("}", "'>");
}
document.getElementById("t").innerHTML = newstr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">{color:#c91d1d}Hello{color}
{color:red}How{color} {color:yellow}are{color} {color:green}you{color}
</div>

Get list values in tag 'a' one by one using JavaScript

Here I am going to make a tag cloud manually.Everything is going well but I face a little problem. Below is my code :
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts">
</div>
</div>
JavaScript :
$(function() {
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
var count_li = $('#vis').find('#tagcloud_list').length+1;
for(var i=0; i < liArray.length ;i++){
for(var j = 0; j < count_li; j++){
if(i == j){
var get_item_value = ($(liArray[i]).text());
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
}
}
}
});
Output of this code is :
Item2
Item2
In this output both contain value 'Item2'.
But I want to get value 'item1' in first tag 'a' and value 'item2' in second tag 'a' .Like :
Item1
Item2
How I can get this?
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts"></div>
</div>
CSS:
.set_text {
height:500px;
width:500px;
background-color:#FFFFFF;
font-family:Arial;
border: 1px solid #FFFFFF;
text-align:left;
}
.tagcloud {
font-size:12px;
text-decoration:none;
color: #FF7600;
}
JS:
$(function () {
var container = $("#vis").find(".set_texts");
$("#tagCloud").find('li').each(function (i) {
$('<a href="" id="tagcloud_list" class="tagcloud tagcloud_li' + i + '"/>').text($(this).text()).appendTo(container);
});
});
Sample: (Fiddle)
Created tag cloud is simple but it's what your code does.
Your code is very complex and thus you won't see the point for sure. I.e.,
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
might be reduced to this:
$("li").each(function() {
var item = $(this);
var text = item.text();
$('<a href="" class="tagcloud_list" id="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">')
.text( text )
.appendTo( $('#vis').find('.set_texts') );
});
Your example of this loop is fetching same information from DOM several times and drops it in one of those cases. That's expensive by means of performance. Next you might reverse way of adding the <a> so you won't need to add it to the target container first just to get query that one to give it back afterwards.
The resulting <a> are all using same ID which is bad, too. So try swapping class and ID.
According to your issue this code seems to be crucial:
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
It is finding all <a> in your target assigning single text to all of them.
Change your Javascript to this.. And I used Jquery..
$(document).ready(function(){
var liArray = $("li");
var i;
for(i=0;i < liArray.length;i++){
$("div.set_texts").append('' + liArray[i].innerHTML + '');
}
});

Categories

Resources