I want to have the text value from a inside a
element.
html:
-
If you use eg. "id" you can do it this way:
(function() {
let x = document.getElementById("idName");
let y = document.getElementById("liName");
y.addEventListener('click', function(e) {
y.appendChild(x);
});
})();
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p id="idName">TEXT</p>
<ul>
<li id="liName">
</li>
</ul>
</body>
<script src="js/scripts/script.js"></script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Where to JavaScript</title>
<!-- JavaScript in head tag-->
<script>
function changeHtmlContent() {
var content = document.getElementById('content').textContent;
alert(content);
}
</script>
</head>
<body>
<h4 id="content">Welcome to JavaScript!</h4>
<button onclick="changeHtmlContent()">Change the content</button>
</body>
Here, we can get the text content of h4
by using:
document.getElementById('content').textContent
Add an Id
property into the P
tag with value like text or something:
function gettext() {
var amount = document.getElementById('text').value;
}
Alternatively, you can also pass the li element itself to your myfunction function as shown:
function myfunction(ctrl) {
var TextInsideLi = ctrl.getElementsByTagName('p')[0].innerHTML;
}
and in your HTML, <li onclick="myfunction(this)">
Do you use jQuery? A good option would be
text = $('p').text();
Try this:
<li onclick="myfunction(this)">
function myfunction(li) {
var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}
Live demo