开发者

Get multiple elements by Id

I have a page with anchor tags throughout the body like this:

<a id="test" name="Name 1"></a>
<a id="test" nam开发者_StackOverflow社区e="Name 2"></a>
<a id="test" name="Name 3"></a>

The ID is always the same but the name changes.

I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I've got to so far:

document.write(document.getElementById("readme").name);

This writes out the name of the first anchor tag. I'm in need of a way to get multiple elements by Id.


Any help is greatly appreciated.


If you can change the markup, you might want to use class instead.

HTML

<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

JS

var elements = document.getElementsByClassName("test");
var names = '';
for(var i = 0; i < elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo


Today you can select elements with the same id attribute this way:

document.querySelectorAll('[id=test]');

Or this way with jQuery:

$('[id=test]');

CSS selector #test { ... } should work also for all elements with id = "test". Вut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id. Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .

For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).


As oppose to what others might say, using the same Id for multiple elements will not stop the page from being loaded, but when trying to select an element by Id, the only element returned is the first element with the id specified. Not to mention using the same id is not even valid HTML.

That being so, never use duplicate id attributes. If you are thinking you need to, then you are looking for class instead. For example:

<div id="div1" class="mydiv">Content here</div>
<div id="div2" class="mydiv">Content here</div>
<div id="div3" class="mydiv">Content here</div>

Notice how each given element has a different id, but the same class. As oppose to what you did above, this is legal HTML syntax. Any CSS styles you use for '.mydiv' (the dot means class) will correctly work for each individual element with the same class.

With a little help from Snipplr, you may use this to get every element by specifiying a certain class name:

function getAllByClass(classname, node) {

    if (!document.getElementsByClassName) {
        if (!node) {
            node =  document.body;
        }

        var a = [],
            re = new RegExp('\\b' + classname + '\\b'),
            els = node.getElementsByTagName("*");

        for (var i = 0, j = els.length; i < j; i++) {
            if (re.test(els[i].className)) {
                a.push(els[i]);
            }
        }
    } else {
        return document.getElementsByClassName(classname);
    }

    return a;
}

The above script will return an Array, so make sure you adjust properly for that.


Here is a function I came up with

function getElementsById(elementID){
    var elementCollection = new Array();
    var allElements = document.getElementsByTagName("*");
    for(i = 0; i < allElements.length; i++){
        if(allElements[i].id == elementID)
            elementCollection.push(allElements[i]);

    }
    return elementCollection;
}

Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.

However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let’s face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.

here is the function from prototype:

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

[Source]


You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.


You should use querySelectorAll, this writes every occurrence in an array and it allows you to use forEach to get individual element.

document.querySelectorAll('[id=test]').forEach(element=> 
    document.write(element);
});


More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.


If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.

One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.

If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.

I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.

If you want a solution that actually finds all IDs of the same name though, then it's this:

function getElementsById(id) {
    const elementsWithId = []
    const allElements = document.getElementsByTagName('*')
    for(let key in allElements) {
        if(allElements.hasOwnProperty(key)) {
            const element = allElements[key]
            if(element.id === id) {
                elementsWithId.push(element)
            }        
        }
    }
    return elementsWithId
}

EDIT, ES6 FTW:

function getElementsById(id) {
    return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}


With querySelectorAll you can select the elements you want without the same id using css selector:

var elems = document.querySelectorAll("#id1, #id1, #id3");


You can get the multiple element by id by identifying what element it is. For example

<div id='id'></div>
<div id='id'></div>
<div id='id'></div>

I assume if you are using jQuery you can select all them all by

$("div#id")

. This will get you array of elements you loop them based on your logic.


No duplicate ids, it's the basis. If you have an html structure as

<a id="test1" name="Name_1">a1</a>
<a id="test2" name="Name_2">a2</a>
<a id="test3" name="Name_3">a3</a>

Nowadays, with ES6, you can select multiple elements with different id's using the map() method:

const elements = ['test1', 'test2', 'test3'].map(id => document.getElementById(id));

console.log(elements);
// (3) [a#test1, a#test2, a#test3] 

Of course, it's easier to select them if they have a same class.
The elements with the different ids are in an array. You can, for example, remove them from the DOM with the forEach() method:

elements.forEach(el => el.remove());


An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".


Below is the work around to submit Multi values, in case of converting the application from ASP to PHP

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
    var Arr_Elements = [];
    Arr_Elements = document.getElementsByClassName("MultiElements");

    for(var i=0; i<Arr_Elements.length; i++) {
        Arr_Elements[i].value = '';
        var Element_Name = Arr_Elements[i].name;
        var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
        var Multi_Elements = [];
        Multi_Elements = document.getElementsByName(Element_Name);
        var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
        if (Main_Element_Type == "CheckBox") {
            for(var j=0; j<Multi_Elements.length; j++) {
                if (Multi_Elements[j].checked == true) {
                    if (Multi_Elements_Values == '') {
                        Multi_Elements_Values = Multi_Elements[j].value;
                    }
                    else {
                        Multi_Elements_Values += ', '+ Multi_Elements[j].value;
                    }
                }
            }
        }
        if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
            for(var j=0; j<Multi_Elements.length; j++) {
                if (Multi_Elements_Values == '') {
                    Multi_Elements_Values = Multi_Elements[j].value;
                }
                else {
                    if (Multi_Elements[j].value != '') {
                        Multi_Elements_Values += ', '+ Multi_Elements[j].value;
                    }
                }
            }
        }
        Arr_Elements[i].value = Multi_Elements_Values;
    }
}

</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
    <table>

        <tr>
            <td>Check Box</td>
            <td>
                <input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
                <input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
                <input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
            </td>
            <td>
                <input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
                <input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
                <input type="hidden" name="SdPart" id="SdPart" value="3451"></input>

                <input type="textbox" name="Test11" id="Test11" value="345111"></input>

                <!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc 
                -->
                <input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
                <input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
                <input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="Submit" name="Submit" id="Submit" value="Submit" />
            </td>
        </tr>
    </table>
</form>

</BODY>
</HTML>


testCB.php 

<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>


Use jquery multiple selector.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>

Link : http://api.jquery.com/multiple-selector/

selector should like this : $("#id1,#id2,#id3")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜