If you want to retrieve the innerHTML of a div (seen beneath) without using getElementByID (considering this website has several div's with 'quote' as an id), but by referring to the 'field name' (field="bid"). How would you do that?
<div nowrap="nowrap" id="quote" class="realtimeDetailLayer" source="lightstreamer"
style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129"
field="bid">0,28</div>
I want to retrieve the information from an existing website. See beneath. Here you can see that several div's have the same ID
<tbody>
<tr>
<td style="text-align:right;width:auto;padding:8px 0px;"><nobr>Ref.</nobr>:</td>
<td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;">
EUR
<strong><div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="reference">350,85
</div></strong>
</td>
<td style="text-align:right;width:auto;padding:8px 0px;"><nobr>Bied</nobr>:</td>
<td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;">
EUR
<div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="bid">0,28</div>
</td>
<td style="text-align:right;width:auto;padding:8px 0px;">
<nobr>Laat</nobr>:
</td>
<td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;">
EUR
<div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamer" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="ask">0,29
</div>
</td>
<td style="text-align:right;width:auto;padding:8px 0px;"><nobr>%</nobr>:</td>
<td class="ext04" style="white-space:nowrap;width:12%;font-weight:bold;">
<div nowrap=nowrap id="quote" class="realtimeDetailLayer" source="lightstreamerGeneratedValues" style="display:inline" table="LS_ProductDetails_TabID" item="X0000010600NL0010379129" field="midchangepercent"><span class="extNegative"><nobr>-50,88 %</nobr></span>
</div>
</td>
</tr>
</tbody>
You can do it by simply parsing the DOM that is by getting parent and children elements.
Try the following:
els = document.getElementsByTagName('div');
for (i=0; i<els.length; i++) {
if (els[i].field == 'bid') {
//do whatever with the bid element here.
}
}
This gets all the divs and checks the field attribute.
This solution is for the worst case scenario where you don't have any way to have unique ids for the elements
var divs = document.getElementsByTagName('div');
function getQuoteHtml(key){
var i;
for(i =0 ; i < divs.length; i++){
if(divs[i].getAttribute('field') == key){
return divs[i].innerHTML;
}
}
}
Demo: Fiddle
you can use a css selector to do that
document.querySelectorAll('[field="bid"]');
Related
I have a situation where I need to calculate sum taking the values from TD id="amount" which will be repeated/duplicated several times. Ajax only takes value from 1st TD and rest is ignored.
// ajax part
function CalculateMonthlySalary() {
var tot = 0;
$("#amount").each(function() {
tot += parseInt($(this).text());
$("#divEstimatedMonthlySalary").html(addCommas(tot.toFixed(0)))
});
}
<tr data-row-id="1" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Basic Salary">Basic Salary</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="2000.00">2000.00</td>
</tr>
<tr data-row-id="2" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Housing Allowance">Housing Allowance</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="2000.00">2000.00</td>
</tr>
<tr data-row-id="3" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Transport Allowance">Transport Allowance</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="1000.00">1000.00</td>
</tr>
<div class="Heading2">Total Monthly Salary</div>
<div style="clear:both;"></div>
<br>
<div style="margin-left:20px;" id="divEstimatedMonthlySalary" class="Web1">0</div>
Any idea where I am doing wrong ?
Just add custom attribute amount into your td tag.
<!-- Like this -->
<td amount ....>xxx</td>
//change the selector in function with custom attribute amount
function CalculateMonthlySalary(){
var tot=0;
//"#amount" to "td[amount]"
$("td[amount]").each(function() {
tot += parseInt($(this).text());
$("#divEstimatedMonthlySalary").html(addCommas(tot.toFixed(0)))
});
}
It's doing this because you are using ID's and not classes. ID's are only to be used for one element. Change it to a class then loop through each to get it work.
id should be unique in a web document. Javascript also assumes this, and thus ignores every element after it has found an element matching to the id.
you should use class name for selecting the td instead.
I have many tbody elemnts like the one bellow, I try to loop through the tbody elements, then I look for the two div elements in order to give them the largest height of them:
<tbody class="form-row">
<tr class="grp-tr djn-tr form-row has_original">
<td style="" class="original">
<p>
</p>
</td>
<td class="grp-td djn-td">
<div class="grp-readonly">
</div>
</td>
<td class="grp-td djn-td">
<div class="grp-readonly">
</div>
</td>
</tr>
</tbody>
why the function bellow does not find div elements?? and how can I get the two div elements?
function myfunction() {
var elements = $(".form-row");
for (i = 0; i < elements.length - 2; i++) {
alert(elements[i].nodeName); // works well, it shows TBODY
var divs = $(elements[i].find("div.grp-readonly")); // Not working
// some code here
}
}
Thanks.
$(elements[i].find("div.grp-readonly")); is incorrect, because you must move .find outside of element elector (in other words messing up code).
Try using $.each for simplicity:
function myfunction() {
$(".form-row").each(function () {
var div = $(this).find('.grp-readonly');
console.log(div);
});
}
myfunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody class="form-row">
<tr class="grp-tr djn-tr form-row has_original">
<td style="" class="original">
<p>
</p>
</td>
<td class="grp-td djn-td">
<div class="grp-readonly">
</div>
</td>
<td class="grp-td djn-td">
<div class="grp-readonly">
</div>
</td>
</tr>
</tbody>
</table>
I am traversing the divs on my page and looking up child elements using find and supplying a classname
select elements and input elements are located, but the 3 TDs I am trying to find are returning nothing
Here is the code snippet
$.each($(".ccypair"), function(index, element) {
var elements = {
selectElement : $(element).find('.selectstyle'),
inputElement : $(element).find('.inputstyle'),
tdElement1 : $(element).find('.decayTime'),
tdElement2 : $(element).find('.price.bidprice'),
tdElement3 : $(element).find('.price.offerprice')
};
});
Now the first two find() lines work fine, but the three tdElement ones below resolve to nothing. Anyone able to tell me where I am going wrong. I suspect for TD I need to have a different selector?
Apologies here is the html
<div class="ccypair" id="ccypairdiv_0">
<form>
<table>
<tr>
<td colspan="2" class="top currency"><select class="ccypairselect"/></td>
<td colspan="2" class="top volume"><input class="ccypairvolume" type="text" value="1m" autocomplete="off"/></td>
<td colspan="2" class="decaytime">00h:00m:00s</td>
</tr>
<tr>
<td colspan="3" class="price bidPrice">---.---</td>
<td colspan="3" class="price offerPrice">---.---</td>
</tr>
</table>
</form>
</div>
<div class="ccypair" id="ccypairdiv_1">
<form>
<table>
<tr>
<td colspan="2" class="top currency"><select class="ccypairselect"/></td>
<td colspan="2" class="top volume"><input class="ccypairvolume" type="text" value="1m" autocomplete="off"/></td>
<td colspan="2" class="top decaytime">00h:00m:00s</td>
</tr>
<tr>
<td colspan="3" class="price bidPrice">---.---</td>
<td colspan="3" class="price offerPrice">---.---</td>
</tr>
</table>
</form>
</div>
Thanks
First check if your jQuery is loading with the $, the try this
//think about structure, it makes your code more legible
$(".ccypair").each(function(index) {
var element = $(this); //each .ccypair found
var elements = {
selectElement : element.find('.selectstyle'),
inputElement : element.find('.inputstyle'),
tdElement1 : element.find('.decayTime'),
tdElement2 : element.find('.price.bidprice'),
tdElement3 : element.find('.price.offerprice')
};
});
cheers
As always a back to basics approach worked. A simple typo was the root cause here. Apologies
On that note. Does jQuery provide a flag so that rather than failing to locate an element and failing silently it will print out an error message. This would be really helpful?
Any ideas why this doesn't work?
http://jsfiddle.net/zk4pc/2/
I'm trying to get it so that everytime there is an element with the class "insert_name", the name is printed from the table.
Could you also help me make the selection more advanced (for instance only using the data from the first tr in the "client-profile" class?
Thanks!
HTML
<body onload="printMsg()">
<div id="api_data" style="display:none;">
<div class="client-profile">
<div class="head icon-5">Customer Details</div>
<table id="client-information">
<tbody>
<tr>
<td class="left">Name:</td>
<td class="color">Matthew Tester
</td>
</tr>
<tr class="dark">
<td class="left">E-mail:</td>
<td class="color">asdfg</td>
</tr>
<tr>
<td class="left">Registration:</td>
<td class="color">2013-11-21</td>
</tr>
<tr class="dark">
<td class="left">Status:</td>
<td class="color"><span class="active">Active</span>
</td>
</tr>
<tr>
<td class="left">Last Login Time:</td>
<td class="color" title="2014-05-28 11:43:46">1 hour ago</td>
</tr>
<tr class="dark">
<td class="left">Last Login From:</td>
<td class="color">123.123.123.123</td>
</tr>
<tr>
<td class="left">Location:</td>
<td class="color">United Kingdom</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="insert_name"></div>
</body>
Javascript
(function printMsg() {
var node = document.getElementsByClassName('insert_name');
node.innerHTML = $('[class*="color"]').eq(0).text();
})();
jsFiddle Demo
The issue is with your node selection. When you select by class name it returns an array of elements. Since you are only looking for the div with that class name, access the first index to reference it.
var node = document.getElementsByClassName('insert_name')[0];
edit
To make this iterate all of the nodes you could take this approach
var nodes = document.getElementsByClassName('insert_name');
var text = $('[class*="color"]').eq(0).text();
for(var i = 0; i < nodes.length; i++){
nodes[i].innerHTML = text;
}
Alternatively, since jQuery is already included, you could remove the body's onload event and just use this
jsFiddle Demo
$(function(){
$('.insert_name').html($('[class*="color"]').eq(0).text());
});
To ensure this only acts on the client-profile class the selector would be
$('.insert_name').html($('.client-profile [class*="color"]').eq(0).text());
If you are just trying to insert the name rather than all of the content, this should do the trick:
$(function() {
$('.insert_name').text($('td:contains("Name:")').next().text());
});
Here is the fiddle:
http://jsfiddle.net/b8LKQ/
Hope that helps!
I added a little more jQuery:
$(function() {
$('[class*="color"]').each(function(){
$('.insert_name').append($(this).text());
});
});
http://jsfiddle.net/zk4pc/7/
Hope that helps!
I have a problem that i want to access the normaltagCmt elements value:
<div id="random no">
<div id="normaltagdialog">
<table style="width:100%; height:100%" border="2px">
<tr style="width:100%; height:13%" align="left">
<td>
<label> {$LANG.TEXT}</label>
</td>
</tr>
<tr style="width:100%; height:59%; vertical-align:middle" align="center" >
<td>
<textarea id="normaltagCmt" style="width:90%; height:90%" ></textarea>
</td>
</tr>
<tr style="width:100%; height:13%">
<td>
<label> {$LANG.COLOR}</label>
</td>
</tr>
<tr style="width:100%; height:15%; ">
<td>
<table style="width:100%;height:100%" cellpadding="2" cellspacing="2">
<tr id="colorPad" align="center">
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
The script i have written above is a jquery dialog and this dialog opens many times.
i want to get the value of normaltagCmt for a particular div with a specific random id.
How can i get that in javascript?
Try $('#random_no #normaltagCmt').val().
i hope by "random no" you mean random number, you cant have a space in a ID and ill use ID14 instead of "random no".
$("#ID14 #normaltagdialog table tr td #normaltagCmt").val()
There can only be one of any ID in javascript, so you could just do $('#normaltagCmt') and it will always only return the one element.
However, if you want to check to make sure that it is a child of an element with a random id (a number that you do not know), then it will get a little trickier.
$("#normaltagCmt").filter(function() {
var valid_parent = false;
var numeric_re = /^\d+$/g;
for( var parent in $(this).parents("div") ) {
if( re.test(this.id) ) {
valid_parent = true;
break;
}
}
return valid_parent;
}
This bit of jQuery will test to make sure that the element with the specified id has a parent div with a numeric id. If it does not, then you will be left with an empty jQuery object.