最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavaScript - innerHTML to change more then first occurrence plus random array - Stack Overflow

programmeradmin0浏览0评论

I have two baffling things going on,

First: Is I’m trying to use the .innerHTML to change more than just the first occurrence.
Second: Is that I’m trying to have a random word replace the .innerHTML.

I've only been able to change the first word let alone all plus the random is a plete fail, any help would be appreciated.

Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>

<script type="text/javascript">

document.getElementById("p1").innerHTML="newWorld()";

function newWorld() {
  var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");

var whichWorld = Math.floor(Math.random()*worlds.length); 

worlds[whichWorld](); 
};

</script>

I have two baffling things going on,

First: Is I’m trying to use the .innerHTML to change more than just the first occurrence.
Second: Is that I’m trying to have a random word replace the .innerHTML.

I've only been able to change the first word let alone all plus the random is a plete fail, any help would be appreciated.

Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>

<script type="text/javascript">

document.getElementById("p1").innerHTML="newWorld()";

function newWorld() {
  var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");

var whichWorld = Math.floor(Math.random()*worlds.length); 

worlds[whichWorld](); 
};

</script>

Share Improve this question asked Aug 9, 2012 at 21:29 JeffJeff 1571 gold badge2 silver badges11 bronze badges 3
  • 2 id is unique. You cannot have three elements with an id of p1. (Or is that a typo?) – Aaron Kurtzhals Commented Aug 9, 2012 at 21:31
  • Your javascript doesn't make much sense, what do you expect the statement worlds[whichWorld](); to do? – Julien Ch. Commented Aug 9, 2012 at 21:35
  • I see thank you, I been using the same id on my reg HTML pages, and didn't know it should be unique and I was able to get a return with something like worlds[whichWorld]() on another code I wrote but it might not have been working like I thought. Only been playing with JavaScript for 2 weeks and HTML for 4 months. – Jeff Commented Aug 9, 2012 at 21:54
Add a ment  | 

5 Answers 5

Reset to default 3

IDs in HTML documents are meant to be unique. The function getElementById will only ever return 1 element, nothing more. For groups of similar elements, you want to give them all a mon class and then use getElementsByClassName (notice the plural Elements vs Element) - this function won't work with IE 8 or earlier, however, so if you need to support IE you would have to do getElementsByTagName and then filter in only those that have the class you want.

As far as the second part of the code, first you are setting the innerHTML to the actual string newWorld() not to the return value of the function (which there is none, as you are not currently returning something from within newWorld) - I think you meant to do document.getElementById("p1").innerHTML = newWorld();. Secondly, the random part of the code is correct and should be choosing a random planet each time. The end of the code is a bit puzzling, however - what exactly are you trying to do there? worlds[whichWorld] is going to be a string (Earth!, etc.) not a callable function. If worlds was an array of functions then the code would work (assuming you also returned it, since you intend to set it as the innerHTML)

In short, something like this would be the "proper" way to set all <span> elements within a parent element to a random planet:

<div id="planets">
    <p>Hello <span>World!</span></p>
    <p>Hello <span>World!</span></p>
    <p>Hello <span>World!</span></p>
</div>

And the Javascript:

var spans = document.getElementById('planets').getElementsByTagName('span');
for(var i = 0; i < spans.length; i++) {
    spans[i].innerHTML = randomWorld();
}

function randomWorld() {
    var worlds = ["Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!"];
    var whichWorld = Math.floor(Math.random() * worlds.length);
    return worlds[whichWorld];
}

And here it is in action. You are clearly new to Javascript so I encourage you to continue to try and learn the basics of it. Eventually, however, you will want to look into libraries such as jQuery which make a lot of the tediousness of writing cross-browser Javascript go away.

According to HTML standard id must be unique, thus getElementById always return 1 element (usually the first found in the HTML.

You could write:

Hello <p class="planet">World!</p>
Hello <p class="planet">World!</p>
Hello <p class="planet">World!</p>

<script type="text/javascript">
  var planets = document.getElementsByClassName("planet")
  for (var i=0; i < planets.length; i++) {
      planets[i].innerHTML = newWorld();
  }

  function newWorld() {
    var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");
    var whichWorld = Math.floor(Math.random()*worlds.length); 
    return worlds[whichWorld]; 
  }
</script>  

I know jQuery is out of the scope of the question, but with a library such as jQuery (and NOT using identical ids) it would be possible to change the content of several element with one statement...

Ids in HTML are supposed to be unique. As such, the getElementById method only returns the first element with the given ID. You've got all the logic right, but you can simplify your answer a bit. Change the ids to classes and use the getElementsByClassName method like so:

Hello <span class="p1">World!</span>
Hello <span class="p1">World!</span>
Hello <span class="p1">World!</span>

<script type="text/javascript">
    var worlds = ["Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!"];

    var pTags = document.getElementsByClassName("p1");
    for (i = 0; i < pTags.length; i++)
    {
        pTags[i].innerHTML = worlds[Math.floor(Math.random() * worlds.length)];
    }
​</script>

DEMO

Note that the getElementsByClassName method doesn't work in IE8 or earlier. So if you want it to be backwards patible with those browsers, you'll either need to use the getElementsByTagName and filter them manually or use jQuery.

JAVASCRIPT DEMO, WORKS ON ALL BROWSERS

JQUERY DEMO

Use a function that gives you a group of elements such as querySelectorAll or getElementsByTagName or getElementsByClassName:

Hello <p class="world">World!</p>
Hello <p class="world">World!</p>
Hello <p class="world">World!</p>

<script type="text/javascript">
var newWorld = function () {
    var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");
    var whichWorld = Math.floor(Math.random()*worlds.length); 

    return worlds[whichWorld]; 
};

var worlds = document.getElementsByClassName("world");

for (var i=0; i < worlds.length; i++) {
    worlds[i].innerHMTL = newWorld();
}

</script>

To mark multiple elements, you should use class attribute. Multiple elements in DOM can have same value of class attribute, but the value of id attribute should be unique.

So the example may look like:

<button id="change-world-btn">Change World</button>
<hr />
<h4>Elements with target class name:</h4>
Hello <span class="world-name">World!</span><br />
Hello <span class="world-name">World!</span><br />
Hello <span class="world-name">World!</span><br />
<hr />
<h4>Element with different class name:</h4>
Hello <span class="other-class">World!</span><br />

<script type="text/javascript">
    var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");

    function newWorld() {
        return worlds[Math.floor(Math.random() * worlds.length)];
    }

    elements = document.getElementsByTagName('span');

    document.getElementById('change-world-btn').onclick = function() {
        world = newWorld();
        for(var i = 0, el; el = elements[i++];) {
            if(el.className == 'world-name') {
                el.innerHTML = world;
            }
        }
    };
​</script>

Try it.

Also you can use document.getElementsByClassName function to simplify the task, but this function is not supported in IE < 9.

发布评论

评论列表(0)

  1. 暂无评论