Javascript gets internal HTML for span by class name
This is the main code format contained in a table named
<div class="leftCol"> ..... <tr id="my_cd"> <td><span class="agt_span">My Code</span></td> </tr> ..... </div> I need to get any text contained in the span class, in this case I need to pull out the text "My code" and then add it to the array. Adding text to an array is not so simple, but I cannot figure out how to pull text. No matter what I try, I can get nothing but an undefined value.
How to get text value Inner HTML for span by class name?
The first question is resolved thank you !!
Deploy the second question first:
<div class="leftCol"> ..... <tr id="my_cd"> <td><span class="agt_span">My Code</span></td> <td> <div> <select name="agt_drp" id="agt_drp" class="agt_drp">...</select> </div> </td> </tr> </div> Let's say I have a select identifier "agt_drp" and I want to get the text of the span class. Is there any way to do this?
Jquery:
var test = $("span.agt_span").text(); alert(test): JavaScript: http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
in javascript vanilla, you can use getElementsByClassName ():
var htmlString = document.getElementsByClassName('agt_span')[0].innerHTML; https://jsfiddle.net/ky38esoo/
Pay attention to the index behind this method.
JQuery:
$('span.agt_span').text(); Pure JavaScript (you need to specify the position of your class element: [0] to get the first one):
document.getElementsByClassName('agt_span')[0].innerHTML; If you have several elements with this class, you can on it:
var elts = document.getElementsByClassName('agt_span'); for (var i = 0; i < elts.length; ++i) { alert(elts[i].innerHTML); } Although getElementsByClassName seems to be supported by the entire main browser, now this is an argument for using it. To make your code compatible and useful, it is better to use the W3C DOM Level 3 Core standard. Document IDL does not describe such a method there!
Therefore please use
var table = document.getElementById("my_cd"); /* id is unique by definition! */ var spans = table.getElementsByTagName("span"); var txt; for(i in spans) { if(spans[i].getAttribute("class").contains("agt_span")){ txt = spans[i].firstChild; /* a span should have only one child node, that contains the text */ } } return txt; This method is not ideal, since you really need to separate the spans[i].getAttribute("class").split(" ") characters into a space and check if this array contains "agt_span".
By the way: innerHTML is also not a DOM attribute. But you can implement something in a compatible and flexible way using the W3C DOM, and you are sure to write efficient and compatible code.
If js programmers used W3C documents, and if Internet Explorer hadn't violated all of these ECMAScript and W3C rules, there would never have been so much incompatibility between all of these browser versions.