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

Expanding Images for Optimal Display in Responsive Design

I have a collection of large images in various sizes that I need to display without any stretching inside a container with set height. The challenge is to make the image fit perfectly within the container without distorting its proportions. I must achieve ...

Is there a way to simulate pressing the ENTER/RETURN key using JavaScript executor in Selenium using Python?

Greetings everyone, I am a newcomer to Python Selenium and currently working on automating a website. However, I have encountered an issue with the search text box of the website as it does not feature any clickable buttons once the text is entered. Here ...

Strategies for patiently waiting for an object to appear before loading the HTML

After logging into my service, I download data from a REST API, and based on that data, I display certain tabs. However, I am experiencing issues with loading the HTML content once the data has been retrieved. The ngif directive at the beginning of the H ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

Exploring a JSON Object with Nested Data

I am trying to recursively parse a JSON object in JavaScript. Below is an example of the JSON structure: const obj = { tag: 'AA', type: 'constructed', value: 'ABCD1', child: [ { tag: 'BB', ty ...

Mastering the art of integrating two applications in Django involves understanding how to properly

Hey there, I'm currently diving into Django and I have a question regarding making my two apps work together. Here's how my folders are structured: mysite/ --/app1 (blog app) --/app2 (a list of users that sign up with a form) --/mysite --db --m ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Handle empty response from endpoint response

I'm facing an issue with a method that subscribes to an endpoint for a response. In some cases, the endpoint returns null and I need to handle this scenario. public list: Array<any>; this.GetList(this.getListRequest) .subscribe( (resp) =& ...

Unveiling the secrets to isolating elements from a list based on distinct characteristics

Currently, I am attempting to scrape job skills from the Wuzzuf website using the following code snippet: result = requests.get("https://wuzzuf.net/search/jobs/?q=data+analysis&a=navbl") src = result.content soup = BeautifulSoup(src, "lx ...

Clickable functionality disabled for form elements

I am encountering an issue with my system development task. The form elements appear to be unclickable, preventing any data entry in the fields. I have attempted moving the form tag above the first div in the code structure below as a troubleshooting step, ...

Is it advisable to use only one base SCSS @use import throughout the entire React application?

Hey there, I've got a question that's been on my mind. I really enjoy using SCSS in React, but for the longest time, I steered clear of variables and mixins because dealing with imports after making changes was a complete nightmare for me (I had ...

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Trouble with Alignment in Bootstrap 3 Form

I'm currently facing an issue with aligning a form group in Bootstrap 3. My goal is to have them aligned vertically, but I am struggling to achieve this. Any help would be greatly appreciated! Please refer to the screenshot below for reference: Her ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

Using the "this" keyword within a debounce function will result in an undefined value

It seems that the this object becomes undefined when using a debounce function. Despite trying to bind it, the issue persists and it's difficult to comprehend what is going wrong here... For instance, in this context this works fine and returns: Vu ...

Tips for customizing the color of the select drop down arrow component:

Is there a way to change the color of the select drop down box arrow part? It needs to be compatible with IE9, Firefox, and other browsers. Currently, the drop down box looks like this: I would like the arrow part to have this appearance: I believe this ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

Update the class of the panel immediately prior to a click event

Is it possible to change the class before the animation starts or when opening/closing the panel? Currently, the class only changes after the animation has finished and the panel is already open or closed. Here is an example: http://jsfiddle.net/0b9jppve/ ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...