This is the basic format of the code the table is contained within a div named
<div class="leftCol">
.....
<tr id="my_cd">
<td><span class="agt_span">My Code</span></td>
</tr>
.....
</div>
I need to be able to get whatever text is contained within the span class, in this case I need to pull the text "My Code" and then add that into an array. Adding the text into an array is not the issue that's easy but I can't figure out how to pull the text. No matter what I try I can't get anything but an 'undefined' value.
How do I get the Inner HTML text value for a span by class name?
First Question solved thanks!!
Second question expand on 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 the select id "agt_drp" and I want to get the span class text. Is there any way to do that?
Jquery:
var test = $("span.agt_span").text();
alert(test):
Javascript:
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
in vanilla javascript, you can use getElementsByClassName():
var htmlString = document.getElementsByClassName('agt_span')[0].innerHTML;
https://jsfiddle.net/ky38esoo/
Notice the index behind the 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 multiples elements with this class, you can loop on it:
var elts = document.getElementsByClassName('agt_span');
for (var i = 0; i < elts.length; ++i) {
alert(elts[i].innerHTML);
}
Though getElementsByClassName seems to be supported by all major browser, that is now argument to use it. To keep your code compatible and usefull, better use the W3C Standard DOM Level 3 Core. The Document IDL does not describe such a method there!
So 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 isn't perfect, as you actually need to split the spans[i].getAttribute("class").split(" ") on space chars and check if this array contains "agt_span".
By the way: innerHTML is no DOM Attribute too. But you can implement anything in a compatible and flexible way using W3C DOM and you will be sure to write effective and compatible code.
If the js programmers had used the W3C Documents and if there weren't no Internet Explorer to break all those ECMAScript and W3C rules, there would never have been that many incompatibilities between all those browser versions.
Related
I'm trying to extract data from a JS function that only renders an element's HTML - and I need the element's ID or class.
Example:
JS Element Value:
x = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
I need to do get the element's id or class (in this case the id would be myId).
Is there any way to do this? Strip the tags or extract the text via strstr?
Thank you
The easiest thing to do would be to grab the jQuery object of the string you have:
$(x);
Now you have access to all the jQuery extensions on it to allow you to get/set what you need:
$(x).attr('id'); // == 'myId'
NOTE: This is obviously based on the assumption you have jQuery to use. If you don't, then the second part of my answer is - get jQuery, it's designed to make operations like these very easy and tackle compatibility issues where it can too
You may want to take a look at this:
var div = document.createElement('div');
div.innerHTML = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
console.log(div.firstChild.className);
console.log(div.firstChild.id);
I have table in the jsp which is dynamically populated.
I used same id for all the table rows.
In the javascript I want to retreive all the table row elements whose id is "resultRow".
and getElementsByName("resultRow") in js gives empty htmlcollection in IE10
Is there any other way to get the tablerows of matched id
Any help is greatly appreciated
`here is my code snippet
In JSP:
<table id="subSecondTable" cellpadding="0" cellspacing="0">
<c:set var="loopCount" value="0" />
<c:forEach var="vinList" items="${requestScope.vehicleDetailsPO}">
<tr id="resultRow" height="10" class="handCursor"
onclick="rowColorChange('<c:out value="${loopCount}"/>','<c:out value="${vinList.vin}"/>');">
In js:
function rowColorChange(rowNumber,vin){
var rows=document.getElementsByName("resultRow");
var columns;
rowHighlighted=rowNumber;
for(i=0;i<rows.length;i++){
if (i==rowNumber){
rows[rowNumber].style.backgroundColor="blue";
//change the text color for the highlighted row
columns = rows[rowNumber].cells
for(j=0;j<columns.length;j++){
columns[j].style.color = "white";
}
//change the text color for the highlighted row
var previousRowint = parseInt(previousRow);
if (previousRow != rowNumber)
{
columns = rows[previousRowint].cells
for(j=0;j<columns.length;j++){
columns[j].style.color = "black";
}
}
previousRow=rowNumber;
if(vin==''){
vin = rows[parseInt(rowHighlighted)].cells[3].innerText;
}
document.getElementById("txtCopyVin").value=vin;
document.getElementById("txtCopyVin").select();
}else{
rows[i].style.backgroundColor="white";
}
}
if(window.event!=null){
rows[rowNumber].cells(window.event.srcElement.cellIndex).focus();
}
}`
I've just confirmed with my own testing that this is a change that Microsoft seems to have made in IE10 to make it compatible with every other browser on the market. In every other browser, ID and name are different things. But until IE 10, Microsoft chose to do things differently, which caused lots of incompatibilities, as described here. This change fixed my code written for chrome, but seems to have broken code written for IE.
If you instruct your users to turn on "compatibility mode", it should work as before, but that's probably not a good long term solution.
The good news is if you go through and fix this issue in your code by making id's refer to id's and names refer to names, your site will then be compatible with other browsers besides IE.
Looking at your code, it seems you want to replace id="resultRow" with name="resultRow"
Since when were name and id equal? To give an example, how many people have the name John Smith (besides the Doctor)? In spite of that, they all have unique IDs. The same applies to your HTML.
Use <tr name="resultRow"...>, then you can access getElementsByName('resultRow')
This behavior is by design.
name and id are two different things.
In addition, ids must be unique; your HTML is invalid.
You should use class instead, and call getElementsByClassName().
I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.
If I have a span, say:
<span id="myspan"> hereismytext </span>
How do I use JavaScript to change "hereismytext" to "newtext"?
For modern browsers you should use:
document.getElementById("myspan").textContent="newtext";
While older browsers may not know textContent, it is not recommended to use innerHTML as it introduces an XSS vulnerability when the new text is user input (see other answers below for a more detailed discussion):
//POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!!
document.getElementById("myspan").innerHTML="newtext";
Using innerHTML is SO NOT RECOMMENDED.
Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.
document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!
The right way:
span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);
For more information about this vulnerability:
Cross Site Scripting (XSS) - OWASP
Edited nov 4th 2017:
Modified third line of code according to #mumush suggestion: "use appendChild(); instead".
Btw, according to #Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.
EDIT: This was written in 2014. A lot has changed. You probably don't care about IE8 anymore. And Firefox now supports innerText.
If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML might be acceptable:
// * Fine for hardcoded text strings like this one or strings you otherwise
// control.
// * Not OK for user-supplied input or strings you don't control unless
// you know what you are doing and have sanitized the string first.
document.getElementById('myspan').innerHTML = 'newtext';
However, as others note, if you are not the source for any part of the text string, using innerHTML can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.
If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:
var span = document.getElementById('myspan');
span.innerText = span.textContent = 'newtext';
Firefox doesn't support innerText and IE8 doesn't support textContent so you need to use both if you want to maintain cross-browser compatibility.
And if you want to avoid reflows (caused by innerText) where possible:
var span = document.getElementById('myspan');
if ('textContent' in span) {
span.textContent = 'newtext';
} else {
span.innerText = 'newtext';
}
document.getElementById('myspan').innerHTML = 'newtext';
I use Jquery and none of the above helped, I don't know why but this worked:
$("#span_id").text("new_value");
Here's another way:
var myspan = document.getElementById('myspan');
if (myspan.innerText) {
myspan.innerText = "newtext";
}
else
if (myspan.textContent) {
myspan.textContent = "newtext";
}
The innerText property will be detected by Safari, Google Chrome and MSIE. For Firefox, the standard way of doing things was to use textContent but since version 45 it too has an innerText property, as someone kindly apprised me recently. This solution tests to see if a browser supports either of these properties and if so, assigns the "newtext".
Live demo: here
In addition to the pure javascript answers above, You can use jQuery text method as following:
$('#myspan').text('newtext');
If you need to extend the answer to get/change html content of a span or div elements, you can do this:
$('#mydiv').html('<strong>new text</strong>');
References:
.text(): http://api.jquery.com/text/
.html(): http://api.jquery.com/html/
You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:
document.querySelector('#myspan').textContent = 'newtext';
developer.mozilla
Many people still come across this question (in 2022) and the available answers are not really up to date.
Use innerText is the best method
As you can see in the MDM Docs innerText is the best way to retrieve and change the text of a <span> HTML element via Javascript.
The innerText property is VERY well supported (97.53% of all web users according to Caniuse)
How to use
Simple retrieve and set new text with the property like this:
let mySpan = document.getElementById("myspan");
console.log(mySpan.innerText);
mySpan.innerText = "Setting a new text content into the span element.";
Why better than innerHTML ?
Don't use innerHTML to updating the content with user inputs, this can lead to major vulnerability since the string content you will set will be interpreted and converted into HTML tags.
This means users can insert script(s) into your site, this is known as XSS attacks/vulnerabilities (Cross-site scripting).
Why better than textContent ?
First point textContent isn't supported by IE8 (but I think in 2022 nobody cares anymore).
But the main element is the true difference of result you can get using textContent instead of innerText.
The example from the MDM documentation is perfect to illustrate that, so we have the following setup:
<p id="source">
<style>#source { color: red; } #text { text-transform: uppercase; }</style>
<span id=text>Take a look at<br>how this text<br>is interpreted
below.</span>
<span style="display:none">HIDDEN TEXT</span>
</p>
If you use innerText to retrieve the text content of <p id="source"> we get:
TAKE A LOOK AT
HOW THIS TEXT
IS INTERPRETED BELOW.
This is perfectly what we wanted.
Now using textContent we get:
#source { color: red; } #text { text-transform: uppercase; }
Take a look athow this textis interpreted
below.
HIDDEN TEXT
Not exactly what you expected...
This is why using textContent isn't the correct way.
Last point
If you goal is only to append text to a <p> or <span> HTML element, the answer from nicooo. is right you can create a new text node and append it to you existing element like this:
let mySpan = document.getElementById("myspan");
const newTextNode = document.createTextNode("Youhou!"),
mySpan.appendChild(newTextNode);
Like in other answer, innerHTML and innerText are not recommended, it's better use textContent. This attribute is well supported, you can check it this:
http://caniuse.com/#search=textContent
document.getElementById("myspan").textContent="newtext";
this will select dom-node with id myspan and change it text content to new text
You can do document.querySelector("[Span]").textContent = "content_to_display";
Can't be used with HTML code insertion, something like:
var a = "get the file <a href='url'>the link</a>"
var b = "get the file <a href='url'>another link</a>"
var c = "get the file <a href='url'>last link</a>"
using
document.getElementById("myspan").textContent=a;
on
<span id="myspan">first text</span>
with a timer but it just shows the reference target as text not runing the code, even tho it does shows correctly on the source code. If the jquery approch is not really a solution, the use of:
document.getElementById("myspan").innerHTML = a to c;
is the best way to make it work.
const span = document.querySelector("#span");
const btn = document.querySelector("#changeBtn");
btn.addEventListener("click", () => {
span.innerText = "text changed"
})
<span id="span">Sample Text</span>
<button id="changeBtn">Change Text</button>
For this span
<span id="name">sdfsdf</span>
You can go like this :-
$("name").firstChild.nodeValue = "Hello" + "World";
(function ($) {
$(document).ready(function(){
$("#myspan").text("This is span");
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>
user text() to change span text.
I used this one document.querySelector('ElementClass').innerText = 'newtext';
Appears to work with span, texts within classes/buttons
For some reason, it seems that using "text" attribute is the way to go with most browsers.
It worked for me
$("#span_id").text("text value to assign");
I have a HTML file that has code similar to the following.
<table>
<tr>
<td id="MyCell">Hello World</td>
</tr>
</table>
I am using javascript like the following to get the value
document.getElementById(cell2.Element.id).innerText
This returns the text "Hello World" with only 1 space between hello and world. I MUST keep the same number of spaces, is there any way for that to be done?
I've tried using innerHTML, outerHTML and similar items, but I'm having no luck.
HTML is white space insensititive which means your DOM is too. Would wrapping your "Hello World" in pre block work at all?
In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space .
Just a tip, innerText only works in Internet Explorer, while innerHTML works in every browser... so, use innerHTML instead of innerText
The pre tag or white-space: pre in your CSS will treat all spaces as meaningful. This will also, however, turn newlines into line breaks, so be careful.
Just an opinion here and not canonical advice, but you're headed for a world or hurt if you're trying to extract exact text values from the DOM using the inner/outer HTML/TEXT properties via Javascript. Different browsers are going to return slightly different values, based on how the browser "sees" the internal document.
If you can, I'd change the HTML you're rendering to include a hidden input, something like
<table>
<tr>
<td id="MyCell">Hello World<input id="MyCell_VALUE" type="hidden" value="Hello World" /></td>
</tr>
</table>
And then grab your value in javascript something like
document.getElementById(cell2.Element.id+'_VALUE').value
The input tags were designed to hold values, and you'll be less likely to run into fidelity issues.
Also, it sounds like you're using a .NET control of some kind. It might be worth looking through the documentation (ha) or asking a slightly different question to see if the control offers an official client-side API of some kind.
Just checked it and it looks like wrapping with the pre tag should do it.
Edit: I am wrong, ignore me.
You can get a text node's nodeValue, which should correctly represent its whitespace.
Here is a function to recursively get the text within a given element (and it's library-safe, won't fail if you use something that modifies Array.prototype or whatever):
var textValue = function(element) {
if(!element.hasOwnProperty('childNodes')) {
return '';
}
var childNodes = element.childNodes, text = '', childNode;
for(var i in childNodes) {
if(childNodes.hasOwnProperty(i)) {
childNode = childNodes[i];
if(childNode.nodeType == 3) {
text += childNode.nodeValue;
} else {
text += textValue(childNode);
}
}
}
return text;
};
This is a bit hacky, but it works on my IE.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title></title>
</head>
<body>
<div id="a">a b</div>
<script>
var a = document.getElementById("a");
a.style.whiteSpace = "pre"
window.onload = function() {
alert(a.firstChild.nodeValue.length) // should show 4
}
</script>
</body>
</html>
Some notes:
You must have a doctype.
You cannot query the DOM element before window.onload has fired
You should use element.nodeValue instead of innerHTML et al to avoid bugs when the text contains things like < > & "
You cannot reset whiteSpace once IE finishes rendering the page due to what I assume is an ugly bug
If someone could format my last post correctly it would look more readable. Sorry, I messed that one up. Basically the trick is create create a throwaway pre element, then append a copy of your node to that. Then you can get innerText or textContent depending on the browser.
All browsers except IE basically do the obvious thing correctly. IE requires this hack since it only preserves white-space in pre elements, and only when you access innerText.
This following trick preserves white-space in innerText in IE
var cloned = element.cloneNode(true);
var pre = document.createElement("pre");
pre.appendChild(cloned);
var textContent = pre.textContent
? pre.textContent
: pre.innerText;
delete pre;
delete cloned;