<html>
</head>
<body>
<div class="class1">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>
<div class="class2">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>
<button onclick="obj1.changehtml()">changehtml</button>
<script type="text/javascript">
var change= function()
{
}
change.prototype.changehtml=function()
{
// targeting specific elements positions
var paragraph=document.getElementsByClassName("class1");
paragraph[0].innerHTML="hello";
paragraph[1].innerHTML="hell1";
var addthem = paragraph[2].innerHTML = second;
}
var obj1= new change;
</script>
</body>
在上面的程序中我遇到了错误
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
尝试使用property更改第一个类(Class1)中的第二段[1] .innerHTML元素。 我该怎么办?
答案 0 :(得分:1)
在您的代码中,在获得`.class1&#39;之后,您错过了[0].children
元素。此外,您应该注意这返回匹配元素的NodeList而不是单个元素。
如果您之前使用过jQuery,可能会让您觉得这将是本机javascript功能,允许您将dom方法链接到NodeList,但遗憾的是它不是。
var change = function(){}
change.prototype.changehtml = function(){
// targeting specific elements positions
// okay selector
// var paragraphs = document.getElementsByClassName("class1")[0].children;
// okayer selector
// var paragraphs = document.getElementsByClassName('class1')[0].getElementsByTagName('p')
// better more explicit selector
var paragraphs = document.querySelectorAll('.class1 > p');
console.log( paragraphs )
paragraphs[0].innerHTML="hello";
paragraphs[1].innerHTML="hello1";
// second is not defined
var addthem = (paragraphs[2].innerHTML = second);
}
var obj1= new change;
&#13;
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<div class="class1">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>
<div class="class2">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>
<button onclick="obj1.changehtml()">changehtml</button>
&#13;