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

Oops! Material-UI is giving an error because the data grid component needs each row to have a unique id property. There was a row provided in the rows prop that does not have an

I've encountered an error that states: Error: Material-UI: The data grid component requires all rows to have a unique id property. A row was provided without id in the rows prop: Whenever I try to add a new row to the existing rows in the DataGrid co ...

Display a loading spinner on the browser while the form is being submitted

My current project involves using AJAX to retrieve data and populate a form. The data being fetched is quite large, resulting in a delay as it is fetched from the database and filled into the form fields. During this process, I display a loading icon to in ...

When incorporating @babel/standalone, a JavaScript memory limit is exceeded

I am currently working on a React app that I developed using create-react-app. My main goal is to take user input as code and then evaluate it in order to render the output. Here's what I have attempted so far: import React, { Component } from &apos ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

What is the best way to position a button under an h3 heading using the display flex

Inside my div, I have an h3 and a button. The div uses display:flex; with justify-content:center; and align-items:center;. However, the button ends up sticking to the right side of the h3. I attempted placing the button in its own div, but this caused a la ...

Is there a JavaScript equivalent to the explode function in PHP with similar functionality

I'm facing an issue while attempting to split my string in JavaScript, here is the code I am using: var str = 'hello.json'; str.slice(0,4); //output hello str.slice(6,9); //output json The problem arises when trying to slice the second str ...

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...

The latest version is available, but remember to update @react-navigation/bottom-tabs, @react-navigation/stack, and @react-navigation/drawer to at least version 5.10.0

As a newcomer to react-native, I am currently attempting to execute a program using expo but encountering a yellow error message. The error states: 'It seems that you are utilizing an outdated version of the react-navigation library. Please ensure th ...

I am facing an issue with the responsiveness of the mat-card component within a div in

Is it possible to display several small paper cards in a div so that they wrap around the container? ...

The original items are not utilized by jquery-ui autocomplete

I currently have the following setup: class Team { constructor(data) { this.id = data && data.id || null this._title = data && data.title || null } get title() { return this._title } set title(v) { this ...

Exploring the basics of caching in Node.js and Express: a beginner's

Picture an application with numerous users and small sets of data (up to 10 name/value pairs), but the process to access this data involves complex calculations. The concept is based on a system with a 'history' state that is crucial for obtaini ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

React: the function is returning as undefined

Description I am encountering an issue with a function in a functional component, as it keeps returning undefined. Despite having all the necessary data defined and accurate within the function including tableData and subtractedStats. This seems to be a ...

TypeORM issue - UnsupportedDataTypeError

Here is the entity file I'm working with, user.ts: @Entity('users') export class User { @PrimaryGeneratedColumn() id: number | undefined; @Column({ type: 'string', name: 'username', nullable: true }) username: s ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

Turn off client-side hydration in Nuxt.js or Prevent leaking raw data in Nuxt.js

Working on a Web App built with Nuxt.js for Server-Side Rendering poses some challenges. To safeguard my backend data, I turned to asyncData and Axios for communication with the server. However, Nuxt.js inadvertently exposed my backend data to clients th ...

Tips for showing only the date (excluding time) from a get operation in javascript (specifically using node js and mysql)

I recently built a CRUD application using Node.js and MySQL. However, I am facing an issue where I am unable to display the date without the time and in the correct format. { "id": 1, "name": "Rick Sanchez", "dob": & ...

Error TS2322: Cannot assign a variable of type 'number' to a variable of type 'string'

Encountered an issue with TS2322 error while attempting to compile my Angular application. The error occurs when using a variable [link] that represents the index number. When declaring this variable, I use: @Input() link!: string; This link is used as ...