gpt4 book ai didi

javascript - 如何在 DOM 中专门定位元素

转载 作者:行者123 更新时间:2023-12-03 07:59:41 30 4
gpt4 key购买 nike

<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

当尝试使用属性更改第一类(Class1)中的第二段[1].innerHTML元素时。我该如何继续?

最佳答案

在您的代码中,在获取“.class1”元素后,您缺少[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;
<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>

关于javascript - 如何在 DOM 中专门定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34646724/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com