问题
I want to have the text value from a <p>
inside a <li>
element.
html:
<ul>
<li onclick="myfunction()">
<span></span>
<p>This Text</p>
</li>
</ul>
javascript:
function myfunction() {
var TextInsideLi = [the result of this has to be the text inside the paragraph"];
}
How to do this?
回答1:
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)">
回答2:
Do you use jQuery? A good option would be
text = $('p').text();
回答3:
Try this:
<li onclick="myfunction(this)">
function myfunction(li) {
var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}
Live demo
回答4:
change your html to the following:
<ul>
<li onclick="myfunction()">
<span></span>
<p id="myParagraph">This Text</p>
</li>
</ul>
then you can get the content of your paragraph with the following function:
function getContent() {
return document.getElementById("myParagraph").innerHTML;
}
回答5:
<!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
回答6:
HTML:
<ul>
<li onclick="myfunction(this)">
<span></span>
<p>This Text</p>
</li>
</ul>
JavaScript:
function myfunction(foo) {
var elem = foo.getElementsByTagName('p');
var TextInsideLi = elem[0].innerHTML;
}
回答7:
Use jQuery:
$("li").find("p").html()
should work.
回答8:
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>
来源:https://stackoverflow.com/questions/11633951/get-paragraph-text-inside-an-element