get value in an element dynamically using DOM in javascript
Dear all, my issue is this. I have like the alert box to display all the text I have in a element. May I know how I can do it?
My ori idea:
<a onclick="displayt开发者_开发问答ext(something)">testing</a>
function displaytext(something){
alert(something);
}
Can someone please help me to solve this? Thanks.
Use innerHTML
(or innerText
if you don't want the HTML) and this
:
<script>
function displaytext(something) {
alert(something.innerHTML); //alerts 'testing'
return false;
}
</script>
<a onclick="displaytext(this)">testing</a>
Use the innerHTML
attribute, after you've gotten the object using getelementbyid
or similar.
If you are just wanting to display the text you should use innerText
Live example
HTML
<a onclick="displaytext(this)">testing</a><br />
<a onclick="displayOtherText()">I'll display the div innerText</a><br />
<a onclick="displayOtherHtml()">I'll display the div innerHTML</a><br /><br />
<div id="textToDisplay"><span>Some sample</span> text here</div>
JavaScript
<script>
function displaytext(element){
alert(element.innerText);
}
function displayOtherText(){
alert(document.getElementById('textToDisplay').innerText)
}
function displayOtherHtml(){
alert(document.getElementById('textToDisplay').innerHTML)
}
</script>
you should use a simple function like this. but be careful this function takes an element id so this will not work for a class name or a element name.
function sayText(elId) { var html = document.getElementById(elId).innerHTML; if (html != null) alert(html) }
精彩评论