Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively.

Any assistance on how to hide divs properly will be greatly appreciated. Thank you!

let divs = document.getElementsByClassName('test');

for (let x = 0; x < divs.length; x++) {
    let div = divs[x];
    let content = div.innerHTML.trim();
  
    if (content == 'example') {
       div.style.display = 'none';
    }
}
<div class="test">
    ipsum
</div>
<div class="test">
    example
</div>
<div class="test">
    example complete
</div>

Answer №1

To identify and remove the specific div element containing more than just the word "example," you can utilize JavaScript's string.includes() method.

An effective approach is to use "example " within the includes() function. By including a space after "example," only the div with additional content will be removed.

let divs = document.getElementsByClassName('test');

for (let x = 0; x < divs.length; x++) {
    let div = divs[x];
    let content = div.innerHTML.trim();
  
    if (content.includes('example')) {
        div.style.display = 'none';
    }
}
<div class="test">
    ipsum
</div>
<div class="test">
    example
</div>
<div class="test">
    example complete
</div>

Answer №2

Something contemporary…

document.querySelectorAll('.example').forEach((element, index) => {
   if (element.innerText.includes('sample')) {
       element.style.display = 'none';
   }
})
<div class="example">lorem</div>
<div class="example">sample</div>
<div class="example">sample complete</div>

Resources: NodeList.prototype.forEach() String.prototype.includes()

Answer №3

If you need to eliminate the div element that includes a specific search word (verified using includes), as well as other characters, you can save the word in a variable and compare the length of the text with it.

let divs = document.getElementsByClassName('test');
const word = 'example';

for (let x = 0; x < divs.length; x++) {
  let div = divs[x];
  let content = div.innerHTML.trim();
  if (content.includes(word) & content.length > word.length) {
    div.style.display = 'none';
  }
}
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>

Below is an updated version of the code for better readability:

let divs = document.querySelectorAll('.test');
const word = 'example';

divs.forEach(div => {
  const { style, textContent } = div;
  const trimmed = textContent.trim();
  if (trimmed.includes(word) && trimmed.length > word.length) {
    style.display = 'none';
  }
});
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>

Answer №4

Performing div.innerHTML.trim() will extract the entire content of the div element.

https://jsfiddle.net/19xo2yLj/4/

Explore using regular expressions for your search, and consider not just hiding a div based on its class, but rather replacing its contents. Unfortunately, I don't have more information to offer at this time.

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

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in t ...

User Agent Stylesheets do not take effect

Currently, I am working on a simple unordered list project where I am utilizing Material UI. However, there seems to be an issue that I would like some help with. (user agent) html.css The CSS includes the property padding-inline-start: 40px but stran ...

Turn off spellcheck for all material-ui elements

Is there a way to deactivate spellcheck globally for elements in the material-ui library? Before incorporating the material-ui library into my project, I used the code below to turn off spellcheck for all new DOM elements: const disableSpellCheck = funct ...

Is there a way to trigger a function with the onclick event in NextJs?

Working on my NestJS project, I am still a beginner in the field. My current task involves creating a web application that displays a leaflet map with clickable tiles. Each tile should have a button that triggers a specific function when clicked. However, ...

Integrate Geometric Information into PostGIS

Hi there! I'm currently using a combination of postgresql and node.js for my backend operations. I've been trying to insert a point into the database from the frontend, but unfortunately, I keep encountering an error message stating "value too lo ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

unable to download file and missing image display

I need assistance with creating a download link using the anchor tag in my code. However, the link is not working as expected and the image is not displaying either. <td><img src="{{book.book_image}}" alt="{{book.name}}" width= ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...

Arranging divs in a row using jQuery sortable technique

Greetings! I have been attempting to achieve horizontal sorting for two divs but have encountered a couple of issues. Firstly, the divs do not align correctly upon initial page load and secondly, while they can be dragged around, the sortable functionality ...

Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module. How can I achieve this without having to directly call the Anonymous function within the mo ...

"Encountering issue with SCSS variable not being applied to background in file

$enable-grid-classes: false; $enable-cssgrid:true; $deepBlue: #032f3e; body { --bs-body-bg: orange ; } @import "https://fonts.googleapis.com/css2?family=Space+Grotesk:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="463121 ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Incorporating mimes into ASP .NET MVC

Quick question: I've been trying to enable file extensions in my MVC application by editing the Web.config file, but it doesn't seem to be working. Is there anything else I need to do? <system.webServer> <staticContent> <mimeMa ...

"Oops! Looks like there's a reference error - the function you're trying

Javascript: function insertSmiley(a) { var $img = $(a).children('img'); $("#message").insertAtCursor(($("#message").data("wbb").options.bbmode) ? $("#message").data("wbb").toBB($(a)): $(a).html()); return false; } HTML: <a href= ...

Display block disappearance persists even after being set to none

Presented below is my menu design: <div class="span2 main-menu-span"> <div class="well nav-collapse sidebar-nav"> <ul class="nav nav-tabs nav-stacked main-menu"> <li class="nav-header hidden-tablet"><span ...

The error message "Unable to retrieve property 'commands' of undefined (discord.js)" indicates that the specified property is not defined

As I try to incorporate / commands into my Discord bot, I encounter a persistent error: An issue arises: Cannot read property 'commands' of undefined Below is my main.js file and the problematic segment causing the error: Troublesome Segment c ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

How to stop Bootstrap collapsible items from "shifting"

I recently integrated a Bootstrap collapse plugin to manage my list of common inquiries: https://jsfiddle.net/2d8ytuq0/ <ul class="faq__questions"> <li> <a href="#" data-toggle="collapse" data-target="#faq__question_1">..</a> ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...