How to perform an internal search for the id?

Asked

Viewed 908 times

2

How can I know if a certain 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>

  • I don’t know why, but this question seems very similar to this one: http://answall.com/questions/180595/comor-buscar-um-elemento-no-xml-usando-javascript

2 answers

3


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>

3

The way you’re doing it has no need to go through all the elements, it would if you were looking for an element by the attribute class (which can be repeated). A id is unique 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.