Code:

<input id="search"/><button onclick="query()">search</button>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>

for example I enter location1 and click button then it query by those class = adr and get result is location1, how to do it?

2 Answers

2
Eddie On Best Solutions

If you are trying to search the location, you can use filter() to get all elements with class adr and test if their text() contains the value of #search

show() the results.

function query() {
  var search = $("#search").val().trim();        //Get the value of search

  $(".adr").hide().filter(function() {
    return $(this).text().includes(search);
  }).show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" /><button onclick="query()">search</button>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>

1
kasperlauge On

I am not sure what is exactly is meant, but here is a non-jQuery solution for what I think you are asking for:

function query() {
  var els = document.getElementsByClassName("adr");
  var input = document.getElementById("search");
  var content = document.getElementById("content");
  var tag = null;
  for (var i = 0; i < els.length; i++) {
    if (els[i].innerHTML === input.value) {
      tag = els[i];
    }
  }

  // Tag contains the element now
  content.innerHTML = tag.innerHTML;
  return tag;
}

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input id="search"/><button onclick="query()">search</button>
    <p class="adr">location1</p>
    <p class="adr">location2</p>
    <p class="adr">location3</p>
    <p class="adr">location4</p>
    <div id="content"></div>
  </body>

</html>

The element which contain the value searched for is returned by the function, and is also applied to the DOM just to showcase.