Find elements that contain a particular keyword in their href attribute and conceal any others (using JavaScript)

I am attempting to create a search box for a webpage where users can enter a keyword, and my code will search that keyword in the href of all elements. It will then hide any elements that do not contain the keyword in their href.

I have implemented a JavaScript code that reads the text in the href and the search box, and checks if the text in the search box is a substring of the string in the href. I am using the indexOf function in JavaScript to check for substrings.

The expected behavior is that the code should display elements that contain the keyword in their href and hide those that do not. However, currently nothing seems to be happening when the code is executed.

function MyFunction() {
  var container, value, txtvalue, i, searchtxt, get;
  get = document.getElementById("searchtext");
  searchtxt = get.value.toUpperCase();
  container = document.getElementById("back");
  value = container.getElementByTagName("a");
  for (i = 0; i < value.length; i++) {
    txtvalue = value[i].href;
    if (txtvalue.toUpperCase.indexOf(searchtxt) > -1) {
      value.style.display = "";
    } else {
      a.style.display = "none"
    }
  }

}
.back {
  width: 100%;
  height: 625px;
}

.linkbox {
  width: 11%;
  height: 34%;
  background-color: green;
  top: 4%;
  display: inline-block;
  border: 1px solid black;
  margin-left: 2.5%;
  margin-top: 4%;
  left: 3.5%;
  box-shadow: 0px 20px 10px -8px black;
  border-radius: 12px;
}

.text {
  width: 100%;
  top: 50%;
  position: relative;
  text-align: center;
  font-size: 100%;
  overflow: hidden;
}
<body style="margin:0; background-color:yellow;">
  <input type="text" id="searchtext" placeholder="search here" />
  <button class="toclick" onclick="MyFunction()"></button>
  <div class="back" id="back">
    <a href="1-spiderman-far-from-home.html">
      <div class="linkbox" style="background:url('images0.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="2-Aladdin-2019.html">
      <div class="linkbox" style="background:url('images1.jpg'); background-size: 100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="3-venom-2018.html">
      <div class="linkbox" style="background:url('images2.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="4-Alita-battle-angel-2019.html">
      <div class="linkbox" style="background:url('images3.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="5-Antman-and-the-wasp.html">
      <div class="linkbox" style="background:url('images4.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="6-Fantastic-beasts-crime-of-grindelwald-2019.html">
      <div class="linkbox" style="background:url('images5.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>

Answer №1

There were a few errors spotted in your code.

  1. Make sure to use getElementsByTagName instead of getElementByTagName

  2. Remember to use toUpperCase() not just toUpperCase

  3. The correct syntax is value[i].style.display and not a.style.display

Live Example

function MyFunction() {
  var container, value, txtvalue, i, searchtxt, get;
  get = document.getElementById("searchtext");
  searchtxt = get.value.toUpperCase();
  container = document.getElementById("back");
  value = container.getElementsByTagName("a");
  for (i = 0; i < value.length; i++) {
    txtvalue = value[i].href;
    console.log(txtvalue)
    if (txtvalue.toUpperCase().indexOf(searchtxt) > -1) {
      value[i].style.display = "";
    } else {
      value[i].style.display = "none"
    }
  }
}
.back {
  width: 100%;
  height: 625px;
}

.linkbox {
  width: 11%;
  height: 34%;
  background-color: green;
  top: 4%;
  display: inline-block;
  border: 1px solid black;
  margin-left: 2.5%;
  margin-top: 4%;
  left: 3.5%;
  box-shadow: 0px 20px 10px -8px black;
  border-radius: 12px;
}

.text {
  width: 100%;
  top: 50%;
  position: relative;
  text-align: center;
  font-size: 100%;
  overflow: hidden;
}
<body style="margin:0; background-color:yellow;">
  <input type="text" id="searchtext" placeholder="search here" />
  <button class="toclick" onclick="MyFunction()">Search</button>
  <div class="back" id="back">
    <a href="1-spiderman-far-from-home.html">
      <div class="linkbox" style="background:url('images0.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="2-Aladdin-2019.html">
      <div class="linkbox" style="background:url('images1.jpg'); background-size: 100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="3-venom-2018.html">
      <div class="linkbox" style="background:url('images2.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="4-Alita-battle-angel-2019.html">
      <div class="linkbox" style="background:url('images3.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="5-Antman-and-the-wasp.html">
      <div class="linkbox" style="background:url('images4.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>
    <a href="6-Fantastic-beasts-crime-of-grindelwald-2019.html">
      <div class="linkbox" style="background:url('images5.jpg'); background-size:100% 100%;">
        <div class="text"></div>
      </div>
    </a>

Answer №2

<html>
<head>
    <style>
    .back{
        width:100%;
        height:625px;
    }
    .linkbox{
        width:11%;
        height:34%;
        background-color:green;
        top:4%;
        display:inline-block;
        border:1px solid black;
        margin-left:2.5%;
        margin-top:4%;
        left:3.5%;
        box-shadow:0px 20px 10px -8px black;
        border-radius:12px;
    }
    .text{
        width:100%;
        top:50%;
        position:relative;
        text-align:center;
        font-size:100%;
        overflow: hidden;
    }
</style> 
</head>

<body style="margin:0; background-color:yellow;">
    <input type="text" id="searchtext" placeholder="search here" />
    <button class="toclick" onclick="MyFunction()">Click</button>
    <div class="back" id="back">
        <a href="1-avengers-endgame.html">
            <div class="linkbox" style="background:url('images0.jpg'); background-size:100% 100%;">
                <div class="text"></div></div>
        </a>
        <a href="2-joker-2019.html">
            <div class="linkbox" style="background:url('images1.jpg'); background-size: 100% 100%;">
                <div class="text"></div>
            </div>
        </a>
        <a href="3-the-lion-king-2019.html">
            <div class="linkbox" style="background:url('images2.jpg'); background-size:100% 100%;">
                <div class="text"></div>
            </div>
        </a>
        <a href="4-toy-story-4.html">
            <div class="linkbox" style="background:url('images3.jpg'); background-size:100% 100%;">
                <div class="text"></div>
            </div>
        </a>
        <a href="5-frozen-2.html">
            <div class="linkbox" style="background:url('images4.jpg'); background-size:100% 100%;">
                <div class="text"></div>
            </div>
        </a>
        <a href="6-captain-marvel.html">
            <div class="linkbox" style="background:url('images5.jpg'); background-size:100% 100%;">
                <div class="text"></div>
            </div>
        </a>
    </div>
</body>
<script>
        function MyFunction(){
                var  val, txtval, j, search;
                search=document.getElementById("searchtext").value.toUpperCase();
                val = document.getElementById("back").getElementsByTagName("a");

                for(j=0; j <val.length ; j++){
                    txtval = val[j].href.toUpperCase();
                    if(txtval.includes(search))
                    {
                        val[j].style.display="";

                    }
                    else{
                        val[j].style.display="none"
                    }
                }

        }

        </script>

</html>

Answer №3

Check out this trendy design that is fully functional

<html>
  <head>
    <style>
      .back{
          width:100%;
          height:625px;
      }
      .linkbox{
          width:11%;
          height:34%;
          background-color:green;
          top:4%;
          display:inline-block;
          border:1px solid black;
          margin-left:2.5%;
          margin-top:4%;
          left:3.5%;
          box-shadow:0px 20px 10px -8px black;
          border-radius:12px;
      }
      .text{
          width:100%;
          top:50%;
          position:relative;
          text-align:center;
          font-size:100%;
          overflow: hidden;
      }
  </style> 
  </head>
  
  <body style="margin:0; background-color:yellow;">
      <input type="text" id="searchtext" placeholder="explore here" />
      <button class="toclick" onclick="MyFunction()">Discover</button>
      <div class="back" id="back">
          <a href="1-spiderman-far-from-home.html">
            <div class="linkbox" style="background:url('https://upload.wikimedia.org/wikipedia/en/b/bd/Spider-Man_Far_From_Home_poster.jpg'); background-size:100% 100%;">
              <div class="text"></div></div>
          </a>
          <a href="2-Aladdin-2019.html">
            <div class="linkbox" style="background:url('https://images-na.ssl-images-amazon.com/images/I/91A0Svq4X0L._SY445_.jpg'); background-size: 100% 100%;">
              <div class="text"></div>
            </div>
          </a>
          <a href="3-venom-2018.html">
            <div class="linkbox" style="background:url('https://upload.wikimedia.org/wikipedia/en/thumb/a/a6/Venom_%28soundtrack%29.jpg/220px-Venom_%28soundtrack%29.jpg'); background-size:100% 100%;">
              <div class="text"></div>
            </div>
          </a>
          <a href="4-Alita-battle-angel-2019.html"&t;            <div class="linkbox" style="background:url('https://upload.wikimedia.org/wikipedia/en/thumb/e/ee/Alita_Battle_Angel_%282019_poster%29.png/220px-Alita_Battle_Angel_%282019_poster%29.png'); background-size:100% 100%;">
              <div class="text"></div>
            </div>
          </a>
          <a href="5-Antman-and-the-wasp.html">
            <div class="linkbox" style="background:url('https://thumbor.forbes.com/thumbor/960x0/https%3A%2F%2Fblogs-images.forbes.com%2Fmarkhughes%2Ffiles%2F2018%2F06%2FANT-MAN-AND-THE-WASP-new-poster-1200x1777.jpg'); background-size:100% 100%;">
              <div class="text"></div>
            </div>
          </a>
          <a href="6-Fantastic-beasts-crime-of-grindelwald-2019.html">
            <div class="linkbox" style="background:url('https://m.media-amazon.com/images/M/MV5BZjFiMGUzMTAtNDAwMC00ZjRhLTk0OTUtMmJiMzM5ZmVjODQxXkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UX182_CR0,0,182,268_AL_.jpg'); background-size:100% 100%;">
              <div class="text"></div>
            </div>
          </a>
      </div>
  </body>

  <script>
          function MyFunction(){
            var searchtxt = document.getElementById("searchtext").value;
            var value = document.getElementById("back").getElementsByTagName("a");

            for(i = 0; i < value.length; i++){
              var txtvalue = value[i].href.toUpperCase();
              if(txtvalue.includes(searchtxt.toUpperCase())){
                    value[i].style.display="";
                }
                else{
                  value[i].style.display="none"
                }
            }
          }
  </script>

  </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing web development: Employing HTML templates to dynamically enhance website performance

My task involves the redesigning of an existing website (foo.com) using .NET and C#. The website caters to multiple companies such as abc.com, def.com, ghi.com, etc. Currently, the website utilizes html templates specific to each company's website in ...

Optimize several projects or pages with RequireJS

How can I improve the efficiency of my multiple requirejs projects? For example, I have this structure below with two main.js in different locations/folders, build/ build.js dev/ index.php core/ js/ main.js libs/ ...

PHP Pear Mail HTML Edition

Despite being able to successfully send emails with text content, I'm facing difficulties in sending HTML emails. The authentication is turned off and Google Apps authenticates based on the server's IP address. $message = 'Blah blah blah&ap ...

Ensure that all MongoDB calls within a loop are completed before proceeding in Node.js

As I'm reading data from a CSV file row by row and making MongoDB calls for each row, I need a way to wait until all the Mongo calls are complete before proceeding to the next function. I have looked into using Promises for this, but find them quite c ...

Ways to modify the shown data in dojox DropDownSelect

I have a DropDownSelect element set up with the following HTML tags: <select id="someId" dojoType="dojox.form.DropDownSelect" > <option>Loading...</option> </select> Now, when the xhr load function is triggered, I want to replace ...

Control the movement of the mouse pointer using javascript

For my University presentation on click-jacking, I came across an intriguing example that I wanted to replicate but didn't know where to start. The whole concept seemed very complex to me. To get a better idea, please take a look at this video: https ...

Execute JavaScript Function in Meteor Once DOM has Finished Loading

Utilizing Bootstrap, I have an input checkbox structured like so: <input type="checkbox" id="toggle" name="toggle"> To convert this checkbox into a switch, I am using Bootstrap Switch as shown below: Meteor.startup(function() { $("[name=' ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Exploring the versatility of jQuery's .on() method in combination

When using the jQuery ajax function to add elements to a page, I encounter an issue with assigning event handlers to newly added elements. After receiving a response from the server on success, I set the content of the element like this: $('#element& ...

Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object: myObj: { foo: 1, bar: 2 } Within a component, I have a computed property set up like so: myObjVals: { get(){ return this.$store.state.myObj ...

Apply a box-shadow to the lower part of the div starting from the center

After much searching, I finally found a preview of what I had in mind. Unfortunately, I couldn't find the right words to describe it. Here is the link to the image for reference: https://i.sstatic.net/t2q27.png Thank you in advance for your help. ...

What is the best method for generating a large number of Express.js routes quickly and efficiently?

Is there a way to efficiently generate multiple routes in Express? I am looking to create routes in the format localhost:3000/${insert address here} Should I use a for loop or is there a built-in feature in Express that can help with this? For instance, ...

Required environment variables are absent in the application form

Currently, I am working on developing a Next.js application and implementing CRUD functionality. However, I encountered an error while creating the "Create" page, which seems to be related to environment detection. Just to provide some context, I am using ...

Utilizing Javascript in conjunction with Selenium and Python for automation tasks

I am attempting to run a piece of javascript code using Python Selenium. Specifically, I am trying to update the value by utilizing execute.script but for some reason, it is not having any effect. I aim to modify the street address as shown below execute_ ...

Dynamic dropdown menu that includes client-side filtering functionality

Does anyone know of an ajax control that meets the following criteria: Enables users to type in for auto-suggestions Dropdown only displays values starting with the characters typed One postback is needed to fetch all data on initial key-in, then f ...

Guide: Sharing Data Between Pages Using onclick Event in JavaScript

1Page.js function TableRow() { let cells = document.querySelectorAll('#recieve-info td'); cells.forEach(cell => cell.onclick = function () { let prevcell = cell.previousElementSibling; if (prevcell) { ...

Having issues with my Angular directive not receiving data from the controller

I am encountering an issue with my controller .controller('Main', ['$scope', function ($scope) { $scope.uiState = {'name': 'test'}; }]) My directive is structured as follows scope: {uiState: '=& ...

Using CSS to target the last child and hover states of an anchor link within an unordered list

I am currently adding styles to the last child of a navigation menu, and I have been successful with this code: .aston-menu-light ul > li:last-child { border:2px solid blue; border-radius: 50px; padding:0 20px 0 20px; } .aston-menu-light ...

Formatting Dates

If I have the following: var date = new Date(parseInt(jsonDate.substr(6))); This returns: Mon Feb 22 1993 00:00:00 GMT+0000 (GMT Standard Time) Is there a way to change this to display as 22-02-1993 instead? ...

Include variables in a JavaScript statement to create conditional functionality

Currently, my code is functioning as expected and appears like this: if (Number.isInteger(number)) { ffmpeg(video.mp4) .on('end', function () { console.log('Screenshots taken'); }) .screenshots ...