简体   繁体   中英

Using getElementById to populate an element on page

Am new with Ajax but I know that you can use getelementbyid to update any element on the page with that id. What I want to know is how do you target a particular element on the page if they all have the same id?

<li class="a">something</li><li class="a">something b</li>

How do I target the second li? since they both using the same id, i cannot use getelementbyid('a') since this will only update the first element with that id.

This is my ajax script

function loadurl(dest) {
var XMLHttpRequestObject = false; 
if (window.XMLHttpRequest) { 
        XMLHttpRequestObject = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
        XMLHttpRequestObject = new 
        ActiveXObject("Microsoft.XMLHttp"); 
} if(XMLHttpRequestObject) { 
        XMLHttpRequestObject.open("GET", dest); 
        XMLHttpRequestObject.onreadystatechange = function() { 

    if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) { 
        document.getElementById("a").innerHTML = 
        XMLHttpRequestObject.responseText; 
        delete XMLHttpRequestObject; 
        XMLHttpRequestObject = null; 
        } 
    } 
    XMLHttpRequestObject.send(null); 
} 

}

and this is link

<a onclick="loadurl('page.php?p=1&id=2')">

Don't repeat IDs, use class names instead. IDs are meant to be unique.

<li class="a">something</li><li class="a">something b</li>

You could then use something like jQuery then, to select them.

$(".a")

Using the same id more than once in an HTML page is invalid HTML. If you had used class names instead:

<li class="a">something</li><li class="a">something b</li>

then you could have used document.getElementsByClassName() to get an array containing all the elements with that class.

To put your response in the second element, use something like this:

document.getElementsByClassName("a")[1].innerHTML = XMLHttpRequestObject.responseText;

or, to put your response in all of the elements with that class name, use something like this:

var els = document.getElementsByClassName("a");
for (var i = 0; i < els.length; ++i)
    els[i].innerHTML = XMLHttpRequestObject.responseText;

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