Reputation:
How to get text from the div?
For example :
<script>
function cahnge() {
alert(document.getElementById('udin'));
}
</script>
<div class="ayah">
<div class="udin" onclick="cahnge()" >udin</div>
</div>
I want to make alert message when the div get clicked and the message is the text of the div.
Thank you.
Upvotes: 0
Views: 134
Reputation: 604
Pass this as an argument in onClick handler
<div class="ayah">
<div class="udin" onclick="cahnge(this)" >udin</div>
</div>
In Javascript
function cahnge(obj) {
alert(obj.innerText);
//alert(obj.innerHTML);
}
In case if the div contains another elements then use 'innerHTML'. If not use 'innerText'.
Upvotes: 1
Reputation: 540
Give it a try
<html>
<body>
<div class="ayah">
<div class="udin">udin</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$elem = $('.udin');
$elem.on('click', function() {
var msg = $elem.html();
alert(msg);
});
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 83
Firstly, you a have named the class udin and not the id. So make this change in the HTML code:
<div class="ayah">
<div id="udin" onclick="cahnge()" >udin</div>
</div>
In Javascript:
function cahnge() {
alert(document.getElementById("udin").innerHTML);
}
InnerHTML helps you retrieve the text.
Upvotes: 0
Reputation: 750
If you use jquery, this is pretty easy to do using .text() - Use an ID on the element to target it specifically, you're using a class, which could have many like it.
$(document).ready(function(){
$("#target").click(function(){
$("#target").text("Hello world!");
});
});
<div class="ayah">
<div id="target" class="udin">udin</div>
</div>
Upvotes: 0
Reputation: 5450
Use getElementByClassName
:
<script>
function cahnge() {
alert(document.getElementsByClassName('udin')[0].innerHTML);
}
</script>
<div class="ayah">
<div class="udin" onclick="cahnge()" >udin</div>
</div>
Upvotes: 0
Reputation: 100
You are close.
getElementById
is checking that the div has an ID
, but your div is a class.
You also need to add .textContent
to get the actual content and not just the div object.
<script>
function cahnge() {
alert(document.getElementById('udin').textContent);
}
</script>
<div class="ayah">
<div id="udin" onclick="cahnge()" >udin</div>
</div>
Upvotes: 2
Reputation: 1550
<script>
function change(aObject) {
alert(aObject.innerHTML);
}
</script>
<div class="ayah">
<div class="udin" onclick="change(this);">udin</div>
</div>
Upvotes: 0
Reputation: 4201
Try this:
<script>
function change(aObject) {
alert(aObject.textContent);
}
</script>
<div class="ayah">
<div class="udin" onclick="change(this);">udin</div>
</div>
Upvotes: 0