Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

javascript - innerHTML isn't working with getElementsByClassName

I'm just a beginner. And I'm trying to use innerHTML. I think I wrote proper code, but it doesn't work. When I click the trigger, the page becomes white and showing the statut : 'connecting' I don't know where is the problem

Please someone help me.

Here are my codes.

HTML CODE

<div class = "head">
<nav>
<a onClick="open()">

<div class = "body">
<div class = "bodyL">
<div class = "newsPnT">

JAVASCRIPT CODE

function open() {
   document.getElementsByClassName('newsPnT').innerHTML = "asdfasdfasdf";
}

What is the problem with my code?

PS: I'm using Firefox Aurora. When I click the trigger, the 'debugger > sources' says, 'waiting for sources.'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getElementsByClassName() returns array with elements.

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

So you need iterate array and set innerHTML like this i.e.

var elements = document.getElementsByClassName('myClass');
Array.prototype.forEach.call(elements, function(element) {
    element.innerHTML = 'Your text goes here';
});

Also a little bonus JSFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...