Reputation: 3
I'm new to javaScript. I want to change list item text using JavaScript that has been assigned class name, but I don't know how.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function change_txt(){
document.getElementsByClassName('Items').innerText="salam";
}
</script>
<title></title>
</head>
<body>
<div id="container">
<ul id="My_List">
<li class="Items">f</li>
<li class="Items">f</li>
<li class="Items">e</li>
<li class="Items">fw</li>
<li class="Items">re</li>
</ul>
</div><button onclick="change_txt()">Change text</button>
</body>
</html>
Upvotes: 0
Views: 3750
Reputation: 6832
Your code is very close but a tip for you that would have enabled you to find this problem quickly.
With in page JavaScript use Chrome or Firefox and the Web Inspector / Development tools (in this case specifically the console
tab) and test your code calls as if you had you would have found your problem.
As with Debugging you would have seen that it returns an array and your just setting a property on that array and not the HTMLElements inside that array.
E.G if you used the Dev tools on this page you can do this.
> document.getElementsByClassName('post-tag');
(14) [a.post-tag.js-gps-track, a.post-tag.js-gps-track, a.post-tag.js-gps-track, a.post-tag, a.post-tag, a.post-tag, span.post-tag.highlight, span.post-tag, span.post-tag.highlight, span.post-tag, span.post-tag, span.post-tag, span.post-tag.highlight, span.post-tag]
Just so you know the clue is in the name get elements by class name
for anything to return more than one item in this case more than one element it will normally use an Array
so from this it comes to very basic use a loop. so your function should look like
function change_txt(){
var itemsA = document.getElementsByClassName('Items');
for(var key in itemsA){
itemsA[key].innerText="salam"
}
}
Upvotes: 0
Reputation: 22776
This works fine :
function change_txt(){
var items = document.getElementsByClassName('Items');
for (var i=0;i<items.length;i++) {
items[i].innerText="salam";
}
}
Upvotes: 1