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

javascript - How to get Id of an element without getElementById - Stack Overflow

programmeradmin1浏览0评论

lets say we got this html scenario:

Please note:

The forms "action" and "method" attributes are omitted on purpose. The "form" tag is just here because in my real project, I have a similar scenario and having the form around all those fields may help in handling the request.

<form id="form1">
    <div id="wrapperDiv">
        <div id="div1">
            <input type="text" id="searchField"/>
        </div>
        <div id="div2">
            <ul>
                <li><a href="javascript:void(0)" onclick="callFunction(this);">Hello</a></li>
            </ul>
        </div>
    </div>
</form>

<script type="text/javascript">
    function callFunction(x)
    {
         //When invoked this function sets the value of "searchField" to the respective link tag innerHTML
         //to set this you cant use something like:
         // var y = document.getElementById("searchField");
    }
</script>

lets say we got this html scenario:

Please note:

The forms "action" and "method" attributes are omitted on purpose. The "form" tag is just here because in my real project, I have a similar scenario and having the form around all those fields may help in handling the request.

<form id="form1">
    <div id="wrapperDiv">
        <div id="div1">
            <input type="text" id="searchField"/>
        </div>
        <div id="div2">
            <ul>
                <li><a href="javascript:void(0)" onclick="callFunction(this);">Hello</a></li>
            </ul>
        </div>
    </div>
</form>

<script type="text/javascript">
    function callFunction(x)
    {
         //When invoked this function sets the value of "searchField" to the respective link tag innerHTML
         //to set this you cant use something like:
         // var y = document.getElementById("searchField");
    }
</script>
Share Improve this question edited Dec 27, 2012 at 10:08 ZeDonDino asked Dec 27, 2012 at 10:02 ZeDonDinoZeDonDino 5,3428 gold badges29 silver badges28 bronze badges 5
  • Is your markup structure likely to change? Are you open to using jQuery? – techfoobar Commented Dec 27, 2012 at 10:04
  • 2 Why are you trying to avoid using getElementById? Please describe your limitations so that we'll be able to give you a proper answer. – Alexander Pavlov Commented Dec 27, 2012 at 10:06
  • @techfoobar yes jQuery libraries can be added. – ZeDonDino Commented Dec 27, 2012 at 10:09
  • 1 @AlexanderPavlov I am making a jsf ui:ponent. The id's are created trough elvariables and this ponent should be reusable so I cannot relay on getElmenentById. – ZeDonDino Commented Dec 27, 2012 at 10:12
  • Will there always be a 1:1 relationship between the a and the input elements (the first input value will have the text of the first a, the second input will have the value of the second a)? – David Thomas Commented Dec 27, 2012 at 10:32
Add a ment  | 

5 Answers 5

Reset to default 3

To get the value of the text input element, we can use the value property of the text input object: text_val = oText.value;

As an example, if we have the following text input element:

<input type="text" name="name" id="txt_name" size="30" maxlength="70">

We can access the value of the element like this:

name = oForm.elements["name"].value;

To obtain a reference to a text input element, here is some sample code:

oText = oForm.elements["text_element_name"]; OR

oText = oForm.elements[index];

In the code above, “index” is the position of the element in the 0-based elements array, and oForm is the form object reference obtained using the document.forms collection:

oForm = document.forms[index];

If you are sure that there is only one input element in your div:

var parent = document.getElementById('div1');
var element = parent.GetElementsByTagName('input')[0];

You can make it easy if using jQuery. You can use:

function callFunction(x) {
    var y = $(this).closest('form').find('input[type="text"]:first');
    y.val(this.innerHTML);
}

to get the search field.

you can use var y= document.getElementsByTagName("input");

One possibility is the following:

function findIndex(el, container) {
    // we can't do anything without a node to work on
    if (!el) {
        return false;
    }
    else {
        // container must be a node, if no container is supplied the body is used
        container = container || document.body;
        // finds all elements of the same tagName as the node
        // (el) passed to the function that are within the container node
        var els = container.getElementsByTagName(el.tagName);
        // iterates through each of these nodes
        for (var i = 0, len = els.length; i < len; i++) {
            // sets the 'data-index' attribute to be equal to 'i'
            els[i].setAttribute('data-index', i);
        }
        // returns the generated index from the 'el' node passed into the function
        return el.getAttribute('data-index');
    }
}

function callFunction(el) {
    // if no el passed in, we stop here
    if (!el) {
        return false;
    }
    else {
        // sets the 'i' variable equal to the value of the 'data-index' attribute
        // if it exists, if it doesn't then we generate it
        var i = el.dataIndex ? el.getAttribute('data-index') : findIndex(el, document.forms.form1);
        // if an index is found (the 'i' variable) we set the value of
        // the 'input' with that index to be equal to the text contained
        // within the clicked link
        if (i) {
            document.getElementsByTagName('input')[i].value = (el.textContent || el.innerText);
        }
        // if no index is returned then we exit here
        else {
            return false;
        }
    }
}

var links = document.getElementsByTagName('a');

for (var i = 0, len = links.length; i < len; i++) {
    links[i].onclick = function(e) {
        e.preventDefault();
        callFunction(this);
    }
}​

JS Fiddle demo.

This does assume that there exists a direct relationship between the nth input and the nth a elements.

I've also moved away from using in-line event-handlers, in order to make maintenance a little easier (and the JavaScript less obtrusive). The first call to the callFunction() gives all the a elements (and a parent/ancestor can be specified to restrict the indexing to only those a elements within a given ancestor node/element), and subsequent calls use the generated data-index attribute (rather than re-generating indices).

References:

  • Element.getAttribute().
  • Element.getElementsByTagName().
  • Element.setAttribute().
发布评论

评论列表(0)

  1. 暂无评论