Javascript 获取元素内的段落文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11633951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get paragraph text inside an element
提问by jay c.
I want to have the text value from a <p>
inside a <li>
element.
我想从元素<p>
内部 获取文本值 <li>
。
html:
html:
<ul>
<li onclick="myfunction()">
<span></span>
<p>This Text</p>
</li>
</ul>
javascript:
javascript:
function myfunction() {
var TextInsideLi = [the result of this has to be the text inside the paragraph"];
}
How to do this?
这该怎么做?
回答by jay c.
Alternatively, you can also pass the li element itself to your myfunction function as shown:
或者,您也可以将 li 元素本身传递给 myfunction 函数,如下所示:
function myfunction(ctrl) {
var TextInsideLi = ctrl.getElementsByTagName('p')[0].innerHTML;
}
and in your HTML, <li onclick="myfunction(this)">
在你的 HTML 中, <li onclick="myfunction(this)">
回答by casraf
Do you use jQuery? A good option would be
你使用 jQuery 吗?一个不错的选择是
text = $('p').text();
回答by Engineer
回答by Tom
change your html to the following:
将您的 html 更改为以下内容:
<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;
}
回答by ankit keshari
<!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:
在这里,我们可以h4
通过使用获取文本内容:
document.getElementById('content').textContent
回答by Karol-X
If you use eg. "id" you can do it this way:
如果你使用例如。“id”你可以这样做:
(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>
回答by j08691
HTML:
HTML:
<ul>
<li onclick="myfunction(this)">
<span></span>
<p>This Text</p>
</li>
</ul>?
JavaScript:
JavaScript:
function myfunction(foo) {
var elem = foo.getElementsByTagName('p');
var TextInsideLi = elem[0].innerHTML;
}?
回答by Triton Man
Use jQuery:
使用jQuery:
$("li").find("p").html()
should work.
应该管用。