简体   繁体   中英

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.'

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 ie

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

Also a little bonus JSFiddle

the className 'open' seemed to the keyword of javascript. I changed the className from 'open' to 'openThis'and that came to be a solution of the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM