Copy multiple element value and append text after in jQuery - javascript

I have price span tags on my page:
<div>
<span class="priceTitle">10.00</span>
</div>
<div>
<span class="priceTitle">15.00</span>
</div>
<div>
<span class="priceTitle">20.00</span>
</div>
I want to append after the span tag the value of the span multiplied by a number.
Somehow like this:
$( ".priceTitle" ).after( $( ".priceTitle" ).val()*1.20 );
...but this is not working.

span does not have a .value property. Use .each() to iterate .priceTitle elements, + operator and .textContent of element to convert string to number; chain .toFixed(2) if you are expecting decimal and two zeroes following product of multiplication.
$(".priceTitle")
.each(function() {
$(this).after(" " + (+this.textContent * 1.20).toFixed(2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="priceTitle">10.00</span>
</div>
<div>
<span class="priceTitle">15.00</span>
</div>
<div>
<span class="priceTitle">20.00</span>
</div>

Related

How do I remove all of the nested span tags within a span tag in javascript?

I have innerHTML that looks like this:
<span class="test"> <span> </span> Hello I am here <span class="test1"> </span> </span>
I want to remove all of the nested span tags so that I get this:
<span class="test"> Hello I am here </span>
I have tried using .replace('', '').replace('', '') in but would have to check the last span somehow and also there could be different spans that are dynamically being made from google docs so it would be better if I could do a replace on all of the spans that is not the first or last span.
Try This
$('.test').find('span').remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="test"> <span>dummy data </span> Hello I am here <span class="test1"> dummay data</span> </span>
This will work
"use strict";
const elm = document.querySelector(".test");
elm.innerHTML = elm.innerText;
console.log(elm.outerHTML);
<span class="test"><span> </span> Hello I am here <span class="test1"> </span> </span>
Use this code to get rid of any empty span elements.
const allSpan = document.querySelectorAll("span");
allSpan.forEach(item => {
if(item.childElementCount === 0 && item.textContent.trim().length === 0){
item.parentElement.removeChild(item)
}
})
<span class="test">
<span> </span> Hello I am here <span class="test1"> </span>
</span>;
You can see the result by inspecting the code in the browser
You can do this by setting the outer span's textContent to it's own textContent - because reading an element's textContent doesn't return any markup tags intersperse with the text.
Resetting textContent also avoids the content of text being parsed by the HTML parser, as it would if used to set the outer element's innerHTML property.
"use strict";
let testSpan = document.querySelector(".test");
testSpan.textContent = testSpan.textContent;
console.log( testSpan.outerHTML);
<span class="test"><span> </span> Hello I am here <span class="test1"> </span> </span>
If you wanted to you could replace consecutive whitespace characters witha single space character before assigning back textContent.

map multiple div elements into array

Faced with mapping problem, it returns for me a blank array with two empty elements. Having a button where on click it gets related div block, then I'm trying to get type and number and push them into array. What I am doing wrong here?
<div class="chapter">
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
</div>
function func(el) {
let block = $(el).closest("div.chapter")
let arr = $(block.find('.contact')).map(function () {
let val = $(this).find('.type, .number').val();
return val;
}).get();
console.log(arr) //result: ["", ""]
}
The .val() method is primarily used to get the values of form elements such as input, select and textarea. You need to use text() method for this, as text() string containing the combined text of matched elements.
Using .val() on span element:
console.log( $('.type').val() )
// Return empty string
console.log( typeof $('.type').val() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Using .text() on span element:
console.log( $('.type').text() )
// Returns '2'
console.log( typeof $('.type').text() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="type">2</span>
Also call them individually for each element like this:
let arr = block.find('.contact').map(function() {
let type = $(this).find('.type').text().trim();;
let number = $(this).find('.number').text().trim();;
return { type, number};
}).get();
This will return you array of objects, where each object has text content of type & number class elements.
DEMO:
let arr = $('.span').find('.contact').map(function() {
let type = $(this).find('.type').text().trim();
let number = $(this).find('.number').text().trim();
return { type, number};
}).get();
console.log( arr )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
Your code does not match with the HTML markup you have provided. You can simply loop through all the element with class contact and find the element inside with specific class to from the object.
Please Note: The span element does not have the value property, you have to use .text().
function func() {
let arr = $('.contact').map(function () {
return {
type: +$(this).find('.type').text().trim(), //find text and convert to number using +
number: +$(this).find('.number').text().trim()//find text and convert to number using +
}
}).get();
console.log(arr);
}
func();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span">
<div class="contact">
<span class="type">
2
</span>
<span class="number">
1111111111
</span>
</div>
<div class="contact">
<span class="type">
4
</span>
<span class="number">
33333333333
</span>
</div>
</div>
you can use simple JavaScript it's easy!
document.querySelectorAll(".contact").forEach((elm)=>{
arr=[] ;
arr.push(elm.children[0].innerText);
arr.push(elm.children[1].innerText);
console.log(arr)
})

jquery - select an element with specific content

I have an html structure like this:
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
In my javascript code, I need to get an <span> element with class content that has exactly 1 or 2 , ..., 100
I tested jquery .contains method, but this returns all elements that have for example 1. such as 1, 12, ....
You can use filter method which accepts a callback function applied to every item.
var array=$('.test').find('.content').filter(function(){
return $(this).text().trim()==100;
});
console.log(Array.from(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
You can proceed in the following manner:
$('.content').each(function(){
if($(this).html() == "2")
{
console.log("THE SPAN WITH 2 IS ");
console.log($(this)[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
What we do here is check through the content class of the spans and check if their inner html is 2 and if it is we console.log it.
You can use the vanilla .indexOf() method.
The indexOf method takes a parameter of the string you want to find and returns either the index (if it's found), or -1 if it's not.
var myEl = document.querySelector(".test"):
for loop...
if( myEl.innerHTML.indexOf(2) != -1 ){
console.log("This element contains the number 2")
}
You can use .filter(), get and check .textContent or .innerHTML of element, at .filter() callback you can use RegExp N$ where N is number to match. For example, to match elements having "1" or "2" set at .textContent you can use RegExp /1$|2$/; to match "100", /100$/; with RegExp.prototype.test()
var filtered = $("span.content").filter((_, {textContent}) =>
/1$|2$/.test(textContent));
filtered.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
You can do something like this..
$('.test').each(function() {
if($(this).text == '1')
{
var a = $(this).html();
}
});
a will now contain the html of that span which contains your text.

Check for number of html element then run a function

I have three different scenario where the span element presents.
No child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here</div>
</div>
One child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here <span class="inside"> please.</span></div>
</div>
Multiple child span element with same class name
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
I want to run the following function:
var len = $('span.inside').get(0).nextSibling.length;
console.log(len);
Because the span class can be present once or multiple times, or not at all, I want to check for the presence of the span. Then based on the number of times the span element is there, I would need to run the function for all the span element.
How would I achieve this?
var length = $('span.inside').length;
if (length > 0) {
$('span.inside').each(function() {
var len = $(this).get(0).nextSibling.length;
console.log(len);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
Use class and get length.
For many span use .each() to iterate over
I want to check for the presence of the span.
You can achieve this by checking the length property of the selector:
var $spans = $('span.inside');
var numberOfSpans = $spans.length;
Based on the number of times the span element is there, I would need to run the function for all the span element
This is a simple if statement, then you can use each() to loop over the elements in a selector:
if (numberOfSpans > 5) { // 5 just an example
$spans.each(function() {
// do something with the span here...
});
}

Remove / (slash) from dom using jquery/javascript

I have dom structure like
<div class="container">
<span> test1 </span>
/
<span> test2 </span>
/
<span> test3 </span>
</div>
which produces output like
test1/test2/test3
i am able to remove the span .. but not able to remove the slash from dom.. can any one please help me to remove the slash from dom so i can get output like
test1test2test3
You can get all .contents() of the element including Node.TEXT_NODE afterwards .filter() can be used to get text nodes then use .remove().
$('.container').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<span>test1</span> /
<span>test2</span> /
<span>test3</span>
</div>
You can iteratate .childNodes of parent .container element, check if .textContent of current node contains "/", if true call .parentElement.removeChild with current node as parameter.
var container = document.querySelector(".container");
for (let node of container.childNodes) {
if (node.textContent.indexOf("/") > -1) {
node.parentElement.removeChild(node)
}
}
<div class="container">
<span> test1 </span> /
<span> test2 </span> /
<span> test3 </span>
</div>
You can make use of children() function and edit the container HTML.
var $container = $('.container');
$container.html($container.children());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<span>test1</span>
/
<span>test2</span>
/
<span>test3</span>
</div>

Categories

Resources