How to verify if a node contains plaintext with jsoup?

Is there a way to determine if a node in jsoup has plain text without including link text, instead of using the Element.hasText() method? Any suggestions would be greatly appreciated. Thank you

Answer №1

One way to achieve this is by utilizing regex, as demonstrated below:

final String html = "<p><span>spantext</span></p>"; // p-tag with no own text, but a child which has one
Document doc = Jsoup.parse(html);

// Check if the 'p'-tag has own text
boolean hasText = doc.select("p").is("p:matchesOwn(^$)"); // --> true, p has no own text

If the element contains some text, the result will be false:

final String html = "<p>owntext<span>spantext</span></p>";
Document doc = Jsoup.parse(html);

// Check if the 'p'-tag has own text
boolean hasText = doc.select("p").is("p:matchesOwn(^$)"); // --> false, p has some own text

Alternatively, you can use the following method:

public static boolean hasOwnText(Element element)
{
    return !element.ownText().isEmpty();
}

When using the provided html and doc instances from above, you can determine the outcome like so:

boolean hasText = hasOwnText(doc.select("p").first())

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

Creating two dropdown menus from a PHP array

Currently, I have a PHP array structured like this. $food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday")); My task is to create two ...

Encountering the issue "net.serenitybdd.core.exceptions.SerenityManagedException: No session ID" when attempting to run the scripts

I was having success with my script until last week, however this week I suddenly received the following error. Can anyone provide guidance? net.serenitybdd.core.exceptions.SerenityManagedException: A runtime error occurred : No active session with ID b3 ...

Creating a dynamic PageFactory WebElement with placeholder symbols

In my scenario, I am generating locators dynamically based on the element chosen from a list. For example, here is a sample generated ID: Function:TableName:0:submenuAction The number 0 represents the counter, indicating the selection of the first eleme ...

In Internet Explorer, when utilizing a table-cell with a variable height, the position should be set to absolute for

I'm struggling with getting a uniform height in my horizontal layout using display: table-cell. While it looks great in Chrome, I can't seem to get Internet Explorer to display it the same way. Check out this link for reference This is how I wa ...

Implementing css padding to text preceding images

My content includes text and images in a mix, and I wish to add CSS margin to elements that appear directly before and after the images. Unfortunately, the placement of these elements can vary and is beyond my control. The code snippet below demonstrates ...

Activate the Twitter Bootstrap Lightbox when the page is loaded

Is there a way to make my twitter bootstrap lightbox automatically trigger when the HTML page loads? Currently, I have this script in my 'main.js' file: function lightbox(){ $('#myLightbox').lightbox(); }; I heard that I can us ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...

Idea: Develop a bookmarklet that generates a header form and deletes it upon submission

After much contemplation and experimentation, I have been grappling with the idea of creating a bookmarklet that displays a header when clicked on any webpage. This header will contain a small form that submits its contents to a server before disappearing. ...

Need at least one form input field out of three to be completed

Currently, I am developing a database program where users are required to enter some of their contact information. <form action="add_action.php" method="POST"> <div class="modal-body"> Name: <br> ...

Issue with Selenium Testing: Struggling to choose a date from the calendar options

For some reason, I am facing an issue where I can't seem to select the date value from the calendar list. However, all the other tests are working perfectly fine. import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

I'm facing an issue with my LAMP stack where the image appears when I access it through a URL, but doesn't seem to load when I try to load it using jQuery

My PHP file is located at path/renderer/renderImage.php and it generates a PNG image that displays correctly in the browser when I visit the URL directly. However, when I try to load this image into a DIV using jQuery from path/index.html with the followin ...

Dynamic card resizing to fit changes in window size

Hey, I'm currently working on a card layout and have hit a roadblock. I'd like the images to shrink as the window size decreases proportionally. Goal: Images should decrease in size until 600px width while staying centered up to that point. I& ...

Are there any other CSS properties that can achieve the same functionality as "contain: content;"?

Searching for an alternative to the contain: content; CSS property that is compatible with older browsers. Is there a solution out there? Perhaps a CSS hack or workaround? ...

Using sandboxed iframes in HTML for secure `src` loading on Internet Explorer 11 and Microsoft Edge

Is there a way in IE11/Edge with HTML5 to populate a sandboxed iframe (<iframe sandbox></iframe>) with HTML without using a src url? I am searching for a solution similar to srcdoc that is compatible with all other modern browsers. Attempting ...

Introducing the new and improved SweetAlert 2.0, the ultimate solution for

I am currently utilizing SweetAlert2.0, known as "This One" <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> It is functioning properly; however, I would like to display a table, div, or HTML element within this swe ...

Safely render user-generated HTML content within a React application to prevent cross-site scripting vulnerabilities

A unique situation has arisen in our React app where a user inputs a string that is displayed to other users. The challenge lies in searching for specific characters within the string and replacing them with HTML elements. For example, transforming the wor ...

What is the best way to add a custom class alongside cdk-overlay-pane for a material menu in Angular 7?

I have a specific requirement to create a mega menu using Angular Material Menu. I attempted to apply some custom styling to the cdk-overlay-pane using my own class, but it did not work as expected. I tried to add a custom class to the mat-menu element us ...