javascript 如何获取内部html值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4321380/
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
How to get the inner html value
提问by sampath
var str_f = document.getElementById("" + j + "").innerHTML;
<p>
<span style="color: red">advertising cctv/bust</span>
<span style="color: red">a</span>tion
</p>
how can i get the value
我怎样才能得到价值
回答by rahul
If you want to get the innerHTML of the <p>tag then give it an id and then use the following code
如果你想获得<p>标签的innerHTML,那么给它一个id,然后使用下面的代码
<p id="para1"><span style="color: red"> advertising cctv/bust</span><span style="color: red">a</span>tion </p>
document.getElementById("para1").innerHTML;
If you want to get text content inside the element then you can use
如果要在元素内获取文本内容,则可以使用
var elem = document.getElementById("para1");
var elementText = x.innerText || x.textContent
回答by Zachary
This won't work, your doing a getElementById but you don't have any elements with Id's...
这行不通,您执行 getElementById 但您没有任何带有 Id 的元素...
回答by Mahendra Liya
Firstly, to get the innerHTML value of any tag, you either need that tag to have its 'id' property or 'name' property set.
首先,要获取任何标签的 innerHTML 值,您需要该标签具有其 'id' 属性或 'name' 属性集。
Then you can respectively use the 'document.getElementById(yourTagIdValue).innerHTML' or 'document.getElementByName(yourTagNameValue).innerHTML' to fetch the value of the required tag.
然后你可以分别使用'document.getElementById(yourTagIdValue).innerHTML'或'document.getElementByName(yourTagNameValue).innerHTML'来获取所需标签的值。
For eg.
例如。
Sampath
桑帕斯
So, you can get the innerHTML of this tag as follows:
所以,你可以得到这个标签的innerHTML如下:
document.getElementById("lblName").innerHTML.
document.getElementById("lblName").innerHTML。
Also, do kindly note that there is a difference for HTML tags for which you can use the 'innerHTML' property and 'value' property.
另外,请注意,您可以使用“innerHTML”属性和“value”属性的 HTML 标签有所不同。
Regards, Mahendra Liya.
问候,马亨德拉莉亚。
回答by Sijan
You haven't mention the ID anywhere in the Tags so you cannot use getElementsById.
您没有在标签中的任何地方提及 ID,因此您不能使用 getElementsById。
You can get the innerHTML of the < p > by using getElementsByTagName.
您可以使用getElementsByTagName获取 < p > 的innerHTML 。
Here is how we use it. Syndtax: var elements = document.getElementsByTagName(name);
这是我们如何使用它。语法:var elements = document.getElementsByTagName(name);
In your case:
在你的情况下:
var pElement = document.getElementsByTagName('p')[0];
var pElement = document.getElementsByTagName('p')[0];
var pElementHtml = pElement.innerHTML;
var pElementHtml = pElement.innerHTML;
if you need just the text, you can do
如果你只需要文字,你可以做
var pElementText = pElement.innerText || pElement.textContent;
var pElementText = pElement.innerText || pElement.textContent;
Hope its useful for someone.
希望它对某人有用。
-Sijan
-Sijan

