Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from

No results were found for this query: <em class="querytext">
to
"No results were found by hello world!
, but the catch is that I cannot directly edit the HTML code. Is there a way to achieve this using CSS or JavaScript? Maybe using an if condition to detect the specific string and then replacing it upon page load? For example, if the text equals
No results were found for this query:
, then display
"No results were found by hello world!"
.

<div class="search-results">
    <h2>No results were found for this query: <em class="querytext"></em></h2>
</div>

Answer №1

If you're looking to manipulate the DOM using JavaScript, here's an example:

<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
      <script type="text/javascript">
          function updateResultText(text) {
            var resultTextEl = document.querySelector('.search-results > h2');
            if(resultTextEl) {
              resultTextEl.innerText = "No results were found by " + text;
            }
          }
    </script>
    <button onclick="updateResultText('hello world!')">Update Text</button>
   <div class="search-results">
     
    <h2>No results were found for this query: <em class="querytext"></em>
    </h2>
  </div>
  </body>
</html>

Here's the JavaScript code snippet needed:

function updateResultText(text) {
            var resultTextEl = document.querySelector('.search-results > h2');
            if(resultTextEl) {
              resultTextEl.innerText = "No results were found by " + text;
            }
          }

To update the text in the 'h2' element, simply call the updateResultText function with your desired text after 'by'.

Answer №2

Try out this vanilla JS solution to modify every h2 element that is a descendant of the class .search-results:

for (let h2 of document.querySelectorAll('.search-results > h2')) {
  if (h2.textContent.search('No results were found for this query') >= 0)
    h2.textContent = 'No results were found by hello world!';
}
<div class="search-results">
  <h2>No results were found for this query: <em class="querytext"></em>
  </h2>
</div>

Answer №3

Previous JavaScript Code

let query = "" // Obtain the username from the backend, URL, or through a simple login form and store it in local storage without using the backend

let newText = 'No results found for this' + query ': <em class="querytext"></em></h2>'

let element = document.querySelector('.search-results h2').innerHTML = newText

Updated to ES5

const query = "" // Obtain the username from the backend, URL, or through a simple login form and store it in local storage without using the backend

const newText = `No results found for this ${query}: <em class="querytext"></em></h2>`

const element = document.querySelector('.search-results h2').innerHTML = newText

Answer №4

To complete your webpage, place the following script tag at the bottom:

<script type="text/javascript">
            var element= document.querySelector('.search-results > h2');
            if(element) {
             if(element.innerText.indexOf("No results were found for this query")>=0)
                 element.innerHtml="Custom message here";
            }
    </script>

After adding that script, remember to include </body></html> tags.

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

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

Error in vue.js: Unable to call this.$emit as it is not a function

export default { mounted() { setTimeout(function() { this.$emit('onLoad') }, 4000); } } //views/Load.vue I want to redirect to another page after the page has been accessed for 4 seconds. <template> <d ...

Is it possible to trigger a server-side event using jQuery in SharePoint 2010?

For my Sharepoint 2010 application, I have been utilizing jQuery to handle most events on the client-side. However, when it comes to saving data to the Sharepoint list and generating a PDF file with that data, I need to switch to server-side processing usi ...

Guide on extracting an Array from JSON in a $.ajax response

I received a JSON value that was converted from an array in the AJAX response. {"Text":"Please provide a value","Email":"Please provide a value"} My goal is to extract the response JSON and display it within a div using $(div).html(): Text-Please provid ...

Step-by-step Guide to Setting pageProps Property in Next.js Pages

When looking at the code snippet provided in .../pages/_app.js, the Component refers to the component that is being exported from the current page. For instance, if you were to visit , the exported component in .../pages/about.js would be assigned as the ...

What is the method for setting tabstops in XHTML?

Is there a way to create a tabstop in an xhtml webpage without using the "&nbsp;" method? I want to avoid putting a space between the ampersand and 'n'. Any suggestions? Edit: My initial post did not display the &nbsp;. I am looking for ...

What is the process for sending a post request with a JSON payload to an external API using Node.js?

I am currently facing an issue while attempting to send a POST request with a JSON payload to an external API using node.js. Below is the code I am using: var express = require('express'); var bodyParser = require('body-parser'); var ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Utilizing asynchronous false in Wordpress Ajax functionality

Is there a way to use the AJAX return value outside the function in WordPress? For example: function get_login_member($) { $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) { data = JSON.parse(data); ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

Setting specific variables in an array with corresponding key-value pairs

I need help with extracting specific columns from a table that has 5 columns. The columns in question are: column1, user_id, column3, column4, and user_exp. Let's say I have the following select query: $mat_sql = mysql_query( "SELECT * FROM users ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

How to send URL parameters to a different page with the help of express and Node.js

Hey there, I'm currently working on a chat app which you can check out here. I'm in the process of enabling users to join specific rooms by typing in a URL like , assuming they are logged in. I manage user login and signup with passwords. Here&ap ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

These specific resources don't have a cache expiration set. Wondering how to properly set a cache expiration for a JavaScript file

I am working on a web application that utilizes external JavaScript files. Upon running Google's page speed tool, I realized that several resources are missing cache expiration settings, including images and CSS files. Can you provide examples of how ...