How to increase div content value? - javascript

I want to increase div value +1 in certain events.How can i get div value and increase it?

this.innerHTML = +this.innerHTML + 1;
DEMO

Given:
<div id="x">42</div>
You can do this:
var $x = $('#x');
$x.text(parseInt($x.text(), 10) + 1);
For your education:
.text()
parseInt() (and always include the radix argument)

If the div's HTML is simply a number:
var element = document.getElementById('yourElementID');
element.innerHTML = parseInt(element.innerHTML, 10)+1;

Here you use below code
In javascript
--------------
var demoInt = $('#divInt').text();
demoInt =parseInt(demoInt);
In HTML
-------
<div id="divInt">111</div>

Related

Subtract number in span

I would like 5 left do -1 e.g. become 4 left.
HTML
<span class="small">5 left</span>
jQuery
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
// Here comes the issue, how do I add the new content?
$(".small:first").attr(minusStock "left");
Question
How do I add the new numberStock number 4 and text left?
A solution in plain Javascript
Array.prototype.forEach.call(document.getElementsByClassName('small'), function (a) {
a.innerHTML = a.innerHTML.replace(/\d+/, function (v) {
return v - 1;
});
});
<span class="small">5 left</span>
You can use replace:
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
console.log(minusStock);
// Here comes the issue, how do I add the new content?
var original = $(".small:first").text();
var toAdd = original.replace(original[0], minusStock);
$(".small:first").text(toAdd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
Use String#replace method with a callback function.
// use text method with callback where second
// argumnet is old text
$(".small:first").text(function(i, txt) {
// replace text with decremented value
return txt.replace(/\d+/, function(m) {
return m - 1;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
UPDATE : With pure JavaSript do something like this.
// since you just want the first element use
// querySelector otherwise you need to use
// querySelectorAll and then need to iterate
// over them
var ele = document.querySelector(".small");
// update text content of span element
ele.textContent = ele.textContent.replace(/\d+/, function(m) {
return m - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
i am not sure if i understood your question, but if i did here is a way to do it , which is pretty close to what you were trying to achieve
var numberStock = parseInt($('.small').text())
var minusStock = numberStock - 1;
$('.small').text(minusStock + ' left');
here is a fiddle in case you want to test around with it
https://jsfiddle.net/09wcjp7b/

Dynamically add new element and change its content

I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.

How to set a div's content to another div's content

So I have two divs
<div id="1"><p>Hello<p></div>
<div id="2"><p>Goodbye<p></div>
And I am wondering if there is a simple technique to set div "1" equal to div "2" ?
So, the end result will be:
<div id="1"><p>Goodbye<p></div>
<div id="2"><p>Goodbye<p></div>
Thanks.
Do exactly that..
var div1 = document.getElementById("1");
document.getElementById("2").innerHTML = div1.innerHTML;
Try it using javascript
document.getElementById("1").innerHTML = document.getElementById("2").innerHTML
to get specific tags within an element use:
var x = document.getElementById("1");
var y = x.getElementsByTagName("p");
or in one line:
document.getElementById("1").getElementsByTagName("p").innerHTML;

get content of element after slicing his span

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

How To Get Font Size in HTML

I was reading a question on here trying to get the font size of a text. The answer they gave was to get the pixel size using a measure method. All i want to be able to do is get the font size value so i can change it.
For example:
var x = document.getElementById("foo").style.fontSize;
document.getElementById("foo").style.fontSize = x + 1;
This example does not work though these two do
document.getElementById("foo").style.fontSize = "larger";
document.getElementById("foo").style.fontSize = "smaller";
The only problem is that it only changes the size once.
Just grabbing the style.fontSize of an element may not work. If the font-size is defined by a stylesheet, this will report "" (empty string).
You should use window.getComputedStyle.
var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
// now you have a proper float for the font size (yes, it can be a float, not just an integer)
el.style.fontSize = (fontSize + 1) + 'px';
If your element don't have font-size property your code will return empty string. Its not necessary that your element should have font-size property. The element can inherit the properties from parent elements.
In this case you need to find the computed font-size. Try this (not sure about IE)
var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;
console.log(computedFontSize);
The variable computedFontSize will return with the font size with unit. Unit can be px, em, %. You need to strip out the unit to do an arithmetic operation and assign the new value.
If you are using Jquery than following is the solution.
var fontSize = $("#foo").css("fontSize");
fontSize = parseInt(fontSize) + 1 + "px";
$("#foo").css("fontSize", fontSize );
Hope this will work.
Making it work for every case
Sometimes (when using media queries for instance) the above answers don't work, here is how to achieve it anyway:
const fontSize = window.getComputedStyle(el).fontSize
The value that you are getting from fontSize is something like "12px" or "1.5em", so adding 1 to that string will result in "12px1" or "1.5em1". You can take the font size and manipulate it with:
var fontSize = parseInt(x);
fontSize = fontSize + 1 + "px";
document.getElementById("foo").style.fontSize = fontSize;
if the html element has inline style, you can using the .style.fontSize to get the font-size!
when the html element doesn't has inline style, you have to using the Window.getComputedStyle() function to get the font-size!
here is my demo codes!
function tureFunc() {
alert(document.getElementById("fp").style.fontSize);
console.log(`fontSize = ${document.getElementById("fp").style.fontSize}`);
}
function falseFunc() {
alert( false ? document.getElementById("fh").style.fontSize : "check the consloe!");
console.log(`fontSize = ${document.getElementById("fh").style.fontSize}`);
}
function getTheStyle(){
let elem = document.getElementById("elem-container");
let fontSize = window.getComputedStyle(elem,null).getPropertyValue("font-size");
// font-size !=== fontSize
console.log(`fontSize = ${fontSize}`);
alert(fontSize);
document.getElementById("output").innerHTML = fontSize;
}
// getTheStyle();
<p id="fp" style="font-size:120%">
This is a paragraph.
<mark>inline style : <code>style="font-size:120%"</code></mark>
</p>
<button type="button" onclick="tureFunc()">Return fontSize</button>
<h3 id="fh">
This is a H3. <mark>browser defualt value</mark>
</h3>
<button type="button" onclick="falseFunc()">Not Return fontSize</button>
<div id="elem-container">
<mark>window.getComputedStyle & .getPropertyValue("font-size");</mark><br/>
<button type="button" onclick="getTheStyle()">Return font-size</button>
</div>
<div id="output"></div>
reference links:
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
It's simple yet helpful! Replace el as needed.
window.getComputedStyle(document.querySelector('el')).fontSize;
Update:
Using Developer tools like in Chrome. It's better.
Please see images attached.
Try this it would definately help you in determining the font size
var elem = document.createElement('div');
var t=document.createTextNode('M')
elem.appendChild(t);
document.body.appendChild(elem);
var myfontSize = getStyle(elem,"fontSize")
alert(myfontSize)
document.body.removeChild(elem);
function getStyle(elem,prop){
if (elem.currentStyle) {
var res= elem.currentStyle.margin;
} else if (window.getComputedStyle) {
if (window.getComputedStyle.getPropertyValue){
var res= window.getComputedStyle(elem, null).getPropertyValue(prop)}
else{var res =window.getComputedStyle(elem)[prop] };
}
return res;
}
we can further use getter and setter to determine if fontsize is changed afterwards by any peice of code
Here is how you get the top-level font-size (associated to html tag):
window.getComputedStyle(document.getElementsByTagName('html')[0]).getPropertyValue('font-size');
It's useful to check if it's the default 16px or not.

Categories

Resources