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

Automating button clicks after a component has loaded in Angular 2+ can be achieved by implementing a

Currently, I am working on implementing an automatic search function in Angular that triggers after a component loads. Right now, the function is triggered by a button click, but I want to automate this process. <button mat-raised-button class="mat-whi ...

Is there a way to ensure that the div is displayed on the same line?

Check out the jsfiddle link provided: http://jsfiddle.net/HE7yT/ I'm trying to align the Image, content, and Amount in the same line. How can I achieve this? The goal is to have "150" displayed on the same line as the picture. var HTML = $(' ...

Finding the "img" id using jQuery

Here is the code snippet I am working with: <div id="popupContactIMG_4179" class="xxxx"> <a id="popupContactCloseIMG_4179">x</a> <img alt="" src="../IMG_4179.jpg" id="id1&q ...

Tips on customizing the CSS responsiveness of your Bootstrap carousel

I have recently installed a Bootstrap theme on my Wordpress site and I am trying to make some CSS adjustments. One issue I am facing is with the carousel. Currently, when I resize the website or view it on a mobile device... The carousel maintains a lar ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

Including an image side by side with clickable text within a list

Check out my progress here: http://jsfiddle.net/dDK6z/ I've experimented with using display:inline(-block), as well as adjusting margins, padding, and more, but I can't seem to get the image to move down or the text to move up. Does anyone have ...

CSS: When using the float: right property, the container does not grow to

I'm having trouble with expanding the comment body that is floated to the right, as my container doesn't expand along with it. Any tips on how I can resolve this issue? For a clearer understanding, please refer to this link: http://jsfiddle.net/ ...

Implementing HTML tags in C# code

Below is an example of HTML script: <h1> This is heading one </h1> <p> This is paragraph. </p> I would appreciate any recommendations on how to add <html></html> tags to the above script using C#. ...

Get a series of numerical inputs from the user and save them into an array

import java.util.Scanner; class HistogramChart { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter the population of data: "); int populationOfData = scan.nextInt(); S ...

What is the best method to determine the total of values stored in a getter function?

I am struggling with finding a way to calculate the total sum of the integer values stored in my getter method. Essentially, I would like the program to add up all the hours worked by each worker and output the combined total. Unfortunately, I am unsure ho ...

Enhance the appearance of your forms with the "Bootstrap

I'm having trouble with the input-group-addon class. My HTML code is dynamically generated using JavaScript and follows the same structure across different pages. However, it works on one page but not on another. I can't seem to figure out why! ...

Is Material UI equipped to handle CSS Container Queries?

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries Recently introduced container queries for CSS are an exciting development. I'm curious if MUI 5.0 already supports them out of the box. It seems that the current SxProps do not in ...

Tips for combining dvloading and required functionalities on the submit button

My form has 2 fields that must be filled out, and I used the required attribute to enforce this rule. Enter A:<input type="text" name="a" required><br> Enter B:<input type="text" name="b" required><br> <button type="submit" cl ...

During testing, the Vuetify expansion panel body is hidden with a display none style

Greetings! I am currently facing an issue while debugging my testing site. The problem is that the expansion panels are not displaying due to a style attribute attached to the div element of v-expansion-panel__body. Strangely, this issue does not occur on ...

Ways to effectively unit test the JSON exception and ensure full coverage of the catch block

Below is an excerpt from the code I am focusing on, particularly the catch block. JSONObject dataObject = new JSONObject(); String content = null; try{ content = dataObject.put(DecisionTreeConstants.EDGE_ACCOUNT_STATUS, processStatusPretty).toString( ...

Swap the image when hovering over it

Is it possible to modify this specific code so that a hover effect is triggered on mouseover? I attempted to look into similar questions and answers, but I found them difficult to understand. Here is the HTML snippet: <a href="RR.html"><img src ...

What makes CSS Overflow: hidden toggle from working initially to suddenly not working?

There seems to be an issue with the code below - it works fine initially, but as soon as I tweak the height values for .Image, it stops functioning as expected. The test image starts overflowing instead of staying hidden, and no matter how many times I a ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

"Enhance User Experience with Multilevel Dropdowns in Bootstrap 4 - Submenus Aligned to the Top

I recently embarked on a project that involved using Bootstrap 4.4, The project is an eCommerce grocery store with departments comprising categories and subcategories. The main menu became very lengthy when using the default code, so I encountered some al ...

The UsernamePasswordAuthenticationToken in Spring Security consistently results in a 403 error code, indicating that the user's

Currently, I am facing an issue with implementing Spring security JWT-based authorization in my Kotlin application. Every time I try to authenticate/login (/authenticate endpoint), the UsernamePasswordAuthenticationToken successfully finds the user in the ...