clone or append a variable in a new div? - javascript

I have this Html <h1 class="count" role="status">Search results 546</h1>
I'm trying to clone only the numerical '546' of that div and display it inside another div 'h2.count'
I manage to call only the numerical value in an alert via:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(0));
Otherwise , when i try to make it display in the div h2.count instead of an alert, it is not working.
I have try the below:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$parsedPrice.appendTo('h2.onlycount');
Any thought of what i am doing wrong ?
Thanks a lot guys !

I guess that your two html elements are unique so, using id's instead of classes (and native js), try this :
html :
<h1 id="count">Search results 541</h1>
<h2 id="onlycount"></h2>
js :
var price = document.getElementById('count').innerText;
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
document.getElementById('onlycount').innerText = parsedPrice;
https://jsfiddle.net/f3rj2bnv/
And if you want to keep on using jQuery (replace "#" with "." if you want or have to use classes instead of ids in your html elements) :
var price = $('h1#count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2#onlycount').text(parsedPrice)

The content used by .appendTo() should be
"a selector expression or as markup created on the fly"
Since in your example neither is true, try this:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2.onlycount').text(parsedPrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount" role="status"></h1>

Can use text(function)
$('h2.onlycount').text(function(_, existingText){
return existingText + $('h1.count').text().replace(/([^0-9\.])/g, '');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount"></h2>

Related

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?
HTML
<html>
<head> </head>
<body>
<div>
<a>
<img id="#hello">
</a>
</div>
<div></div>
</body>
</html>
JS (JQuery)
var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');
// var selectImg = elemFirst.find('img'); <- It working but I want to select manual
selectImg.addClass('some-css');
With Respect
You can use $('child','parent') selector,
var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst); //or just $('img',elemFirst);
Also, your id has a #, it should be just id="hello".
If you need to keep this value in Id, use
var selectImg = $('img[id="#hello"]',elemFirst);
You can use find():
var selectImg = elemFirst.find('img#hello');
But you have an id of the image, so, you just can do this:
$('img#hello')
Because id is unique.
Use find()
elemFirst.find('img#hello');
This will search for direct and nested elements with the provided selector.
Alternatively, you can do
$('div:first #hello')
or even just
$('#hello')
since you are using an id which should be unique.
As in html the id be unique in html so striaghtly write
$("#\\#hello").addClass('some-css');
or
var selectImg = elemFirst.find('img[id="#hello"]');
Fiddle

Javascript handle 2 data attribute

I need to use data attribute in my html
like
<div id="userlist" data-user="A.A.M"></div>
then I need to alert the data-user
I used
var userlist = document.getElementById("userlist");
var show = userlist.getAttribute("data-user");
alert(show);
My question is how to handle many data-user in the html like
<div id="userlist" data-user="A.A.M"></div>
<div id="userlist2" data-user="A.A.M2"></div>
to alert A.A.M and A.A.M2
Thanks in advance and sorry for my bad English.
You could select your elements by attribute.
$("div[data-user]").each(function() {
var user = $(this).data("user");
alert(user);
});
If you have multiple attributes per element (<div data-user='something' data-another='another'></div>), you can also access those in the same way:
$("div[data-user]").each(function() {
var user = $(this).data("user");
var another = $(this).data("another");
alert(user + ", another: " + another);
});
you know how to alert 1, alert 2:
alert at the same time:
var data1 = document.getElementById("userlist").getAttribute("data-user");
var data2 = document.getElementById("userlist2").getAttribute("data-user");
var data = data1 +"\n" + data2; //"\n" can be other separators you like
alert(data)
if you have many of them, you can use jQuery:
add this in your , before any other js code.
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
then :
$("div[id^=userlist]").each(function(){
alert($(this).attr("data-user"));
});
Calling getElementById on both should work. If you want to iterate you can try to use getElementsByTagName or getElementsByClassName. If you want to select any arbitrary element with the attribute data-user, you can either use querySelectorAll, or check out jQuery, and use $("[data-user]") as a selector.
Does that answer your question?

Get id from string using javascript

I have this simple string:
<div id="parent">
<div id="1" class="child">test</div>
</div>
How can I extract the id number (1) from this string?
With JQuery you can
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var str = $('<div id="parent"><div id="1" class="child">test</div></div>');
console.log(str.find(':nth-child(1)').attr('id'));
</script>
Where nth-child is the target you want to get the id
var s = '<div id="parent"> <div id="1" class="child">test</div> </div>';
var d = new DOMParser().parseFromString( s, "text/xml" );
var id = d.firstChild.childNodes[1].attributes['id'];
console.log( id );
var htmlString = '<div id="parent"><div id="1" class="child">test</div></div>';
var number = /id="(\d)"/.exec(htmlString)[1];
console.log(number); //outputs the number
You would have to do a match on the string object that the HTML is stored in. so, if the string is called htmlString, then you would do something akin to
var id = htmlString.match(/id=\"([0-9]+)\"/)
That SHOULD net you the result, but if you deal with any data that is more complex than the example you've been given, you would need a different regex.
<script>
let num = document.getElementById('1')
let ans = parseInt(num.id)
</script>
Although I am unsure as to what you are trying to accomplish, one way of getting of doing this is s to gather all like tagnames ("div" in this case) into an array and select the array index you desire (1 in this case) then reference the id - as follows:
var list=document.getElementsByTagName("div")
alert(list[1].id);

Get content from id inside id?

I have HTML like:
<div id='content'>
<div id='price'>$100</div>
<div id='another'>something</div>
</div>
I can get content from id="content" like.
vl = document.getElementById("content").value;
In this id, I have another id="price". But I cannot get directly content from id="price".
How can I get content from id="price" through id='content'.Thank you.
jQuery:
$("#price").text();
javascript:
document.getElementById("price").innerHTML;
DEMO
You can use as below :
vl = document.getElementById("price").innerHTML;
JSFiddle - Check it out
YOu can also use jquery using .html() or .text() method
Try,
$('#content').html().find('#price').html();
Try this,
var parent = document.getElementById('content');
var childNodes = parent.childNodes;
for(var i = 0, len = childNodes.length;i<len;i++){
if(childNodes[i].id === "price") {
alert(childNodes[i].innerHTML);
}
}
Using jquery,
$("#content > #price").text();
You can get value of price directly as :
v2 = document.getElementById("price").value;
using Jquery,
v1= $('#content').html();
v2=v1.find('#price');
v3=v1.find('#another')
Try this out:- http://jsfiddle.net/adiioo7/C3C4x/1/
var price = document.querySelector("#content #price").innerHTML;
console.log(price);
IDs should only be used when there is one of that item on the page. You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.
Try this way to select,
var vl = document.getElementById("content").getElementsByClassName("price")[0];
HTML
<div id='content'>
<div class='price'>$100</div>
<div class='another'>something</div>
</div>
You need to access the child element through parent element... that is your question right.. i solve it with jquery DEMO
$(document).ready(function(){
var tem = $('#content').children('#price').text();
alert(tem);
});

Categories

Resources