How to perform an internal search by id?

1

How can I find out if a given element exists, via field input ?

Example

<html>

<body>

<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

<pre>Ex.: vaca, boi, porco ou galinha</pre>


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

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

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

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

</body>

<script>
    function busca() {

        var str = document.getElementById('txt').value;

        var obj = document.getElementsByTagName('div');

        for (var i = 0; i < obj.length; i++) {

            var el = o bj[i].id

            if (document.getElementById(el) != "undefined") {

                alert('existe sim');
                break;

            } else {

                alert('não existe');
                break;

            }

        }

    }
</script>

</html>
    
asked by anonymous 16.02.2017 / 18:39

2 answers

2

function busca() {

  var str = document.getElementById('txt').value;
  var obj = document.getElementsByTagName('div');
  var existe = false;

  for (var i = 0; i < obj.length; i++) {
    if (obj[i].id == str) {
      existe = true;
      break;
    }
  }

  if (existe) {
    alert('existe sim');
  } else {
    alert('não existe');
  }

}
<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

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

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

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

<div id='galinha'></div>
    
16.02.2017 / 18:47
2

As you are doing, you do not have to go through all the elements, you would have been looking for an element with the class attribute (which can be repeated). A id is only per page, so if document.getElementById() return something is because the element exists:

function busca() {
  var str = document.getElementById('txt').value;
  
  if(document.getElementById(str))
    console.log(str + ' existe.');
  else
    console.log(str + ' ñ existe');
}
<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

<pre>Ex.: vaca, boi, porco ou galinha</pre>

<div id='vaca'></div>
<div id='boi'></div>
<div id='porco'></div>
<div id='galinha'></div>
    
16.02.2017 / 20:31