Home > Web Front-end > JS Tutorial > How Can I Hide Unmarked Text in HTML Using CSS or JavaScript?

How Can I Hide Unmarked Text in HTML Using CSS or JavaScript?

Barbara Streisand
Release: 2024-11-30 04:13:14
Original
781 people have browsed it

How Can I Hide Unmarked Text in HTML Using CSS or JavaScript?

Hiding Unmarked Text in HTML

You may encounter situations where you have HTML code with text that lacks any surrounding HTML tags. Hiding this text can be challenging, especially if it's not feasible to wrap the text with a div or other tag. Let's address this issue using CSS and JavaScript techniques.

CSS Hack

One solution is to employ a CSS hack that targets the overall font-size of a specific element:

.entry {
  font-size: 0;
}

.entry * {
  font-size: initial;
}
Copy after login

In this code, .entry elements are assigned a font size of 0, effectively hiding all text within them. However, this can be undesirable in situations where you want other elements within .entry to retain their original font size. To selectively hide specific text, you can add a nested selector:

.entry .hidden-text {
  font-size: 0;
}
Copy after login

This approach targets and hides only elements with the .hidden-text class.

JavaScript

Alternatively, you can use JavaScript to dynamically manipulate the DOM and achieve the desired result. For example, you could use the following JavaScript code:

document.querySelector("div.entry p:nth-child(2)").style.display = "none";
Copy after login

In this code, we select the second paragraph (p:nth-child(2)) within the .entry div and set its display property to "none," effectively hiding it.

The choice between CSS and JavaScript depends on the specific requirements of your situation. If it's essential to selectively hide text, then CSS might be a better option. On the other hand, if you need to hide the text dynamically based on certain conditions or user interactions, then JavaScript is more suitable.

The above is the detailed content of How Can I Hide Unmarked Text in HTML Using CSS or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template