Is there a way to determine if content is present within a given div element?

I have created a sample code where clicking on the "Next" button displays the next content of the page. However, if you click one more time on it when there is no content left, an empty page is shown. How can I determine whether content is available inside the div or not?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css" media="screen">
body {background-color:white; font:16px Helvetica, Arial; color:black;}
.pagination {margin:auto; display:block; height:275px; width:65%; position:relative; overflow:hidden;     border:1px solid black;}
</style>
<script>
$(document).ready(function() {
//$('.pagination').children().wrapAll('<div class="content"/>');
$('.next').click(function() {
    var height = 10;
    var current = ($('.content').css('margin-top') || '0px');
    var pag = document.getElementById("page");
    //for(i=0; i<pag.
    $('.content').css('margin-top',current.substring(0,current.length-2) - $('.pagination').height() + 'px');
});
});

function clk()
{
    var idc = document.getElementById("c");
    //console.log(idc);
}

function test()
{
    var idc = document.getElementById("c");
    var tn = idc.childNodes[0];
    var sp = document.createElement("span");
    var range = document.createRange();

    range.selectNode(tn);
    range.surroundContents(sp);

    console.log("test" + sp.offsetTop);

    return false;
}
</script>
</head>
<body>
<div id="page" class="pagination" style="padding:5px">
<div class="content">
    <p>The House of Representatives shall be composed of Members chosen every second Year by the People of the several States, and the Electors in each State shall have the Qualifications requisite for Electors of the most numerous Branch of the State Legislature.</p>
    <p>No Person shall be a Representative who shall not have attained to the Age of twenty five Years, and been seven Years a Citizen of the United States, and who shall not, when elected, be an Inhabitant of that State in which he shall be chosen.</p>
    <p>(Representatives and direct Taxes shall be apportioned among the several States which may be included within this Union, according to their respective Numbers, which shall be determined by adding to the whole Number of free Persons, including those bound to Service for a Term of Years, and excluding Indians not taxed, three fifths of all other Persons.) (The previous sentence in parentheses was modified by the 14th Amendment, section 2.) The actual Enumeration shall be made within three Years after the first Meeting of the <span id="c" onclick="clk()">Congress</span> of the United States, and within every subsequent Term of ten Years, in such Manner as they shall by Law direct. The Number of Representatives shall not exceed one for every thirty Thousand, but each State shall have at Least one Representative; and until such enumeration shall be made, the State of New Hampshire shall be entitled to chuse three, Massachusetts eight, Rhode Island and Providence Plantations one, Connecticut five, New York six, New Jersey four, Pennsylvania eight, Delaware one, Maryland six, Virginia ten, North Carolina five, South Carolina five and Georgia three.</p>
    <p>When vacancies happen in the Representation from any State, the Executive Authority thereof shall issue Writs of Election to fill such Vacancies.</p>
    <p>The House of Representatives shall chuse their Speaker and other Officers; and shall have the sole Power of Impeachment.</p>
    </div>
</div>
<ul>
<li>Previous</li>
<li class="next">Next</li>
<li><a href="" onclick="return test()">Click</a></li>
</body>
</html>

Answer №2

Without reviewing your specific code, it's important to verify if $('#yourdiv').html() is empty or not.

Answer №3

Building on Kaloyan's explanation, here is a code snippet that trims spaces:

if ($.trim($('div').html())) {
    $('p').text('Contains content');
} else {
    $('p').text('Empty');
}

This will ensure that even spaces are trimmed from the content.

Answer №4

If the div's length is 0, it indicates that there is no content within the div. To confirm this, you can also use the following method. Take a look at the example below:

http://jsfiddle.net/Y7t6s/2089/

$("#div_box1").html().trim().length
$("#div_box2").html().trim().length

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

Sending a Nan alert regarding a JSON attribute

I recently completed a project using Angular4 that involves connecting to a nodeExpressJS server to retrieve JSON data and update the object with new information. Below is the onSubmit function from the addemployeeform. onSubmit(formValue: any) { cons ...

Updating parameters in Node.js with mongoose

script.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var scriptSchema = new Schema({ status: {type: String, default: 'INCOMPLETE'}, code: String, createdDate: {type: Date, default: Date.now}, user: {t ...

Creating a custom function that targets a specific element

When working with JavaScript, you may often encounter functions written in the form of document.getElementById("element").someFunction(); or $("element").someFunction(); rather than the traditional someFunction($("element"));. This is similar to a function ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

How to properly align a form with a multi-lined label in HTML and CSS?

I'm looking to create a form label that spans multiple lines and align the inputs with the labels. The goal is for the "Releasse Date" label to display as: Release Date (YYYY-MM-DD): [input box] Here's how it currently looks: https://i.sstatic ...

The issue with utilizing the keyword 'this' in an ajax function

This is some intricate jQuery code at work here. It retrieves data from a PHP file and slides down the results. If the results are already present, it simply slides them down. $('#compatibility h2').click(function(){ var clicked = $(this ...

Is there a way to locate a file by inputting a partial name?

How can I create a search bar that allows me to find files in a folder (songs) by typing only part of the song name? For example, if I type "he," it should show results like "hello" and "hey." Is there a way to take my input and search for it within file n ...

Preventing file overwriting using fs.writefile method

Encountering an issue where the data being saved from a chat room built with socket.io in nodejs is constantly overwritten upon submission of a message. The desired outcome is to append both the username and message to the JSON file as an object, rather th ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...

How can you create a scenario in Angular Material where items in a toolbar transition to the second line exclusively on mobile screens?

Visit the Angular Material website to see how the toolbar appears on a desktop: https://material.angular.io/ https://i.sstatic.net/KPFMv.png On mobile devices, the menu items Components, CDK, and Guides are displayed on the second line, while github, the ...

Incorporating jquery.prettyPhoto results in the script being displayed on the webpage

When I relocate the following script: <script src="js/jquery.prettyPhoto.js"></script> To this location: <script type="text/javascript"> ... </script> The script starts displaying on the page starting from the bold section on ...

Is an array literal considered an object in JavaScript?

As I delve into the depths of JavaScript by reading The Definitive Guide, a statement caught my eye: The most straightforward method to form an array is by using an array literal Surprisingly, it then mentions another approach: An alternate way to g ...

The stylesheet's URL reference to the image is not functioning properly

I'm attempting to showcase images inside a table cell using CSS. Here's what I currently have: HTML: <td class="activity-status status_not_started">Not Started</td> CSS: td.activity-status { font: 0/0 a !important; color: transpar ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

Removing the dividing line between columns in an Antd table: A simple step-by-step guide

Do you notice the lines dividing each table column heading in the image? I want to get rid of these lines from the table. The table component I am using is Antd table. https://ant.design/components/table#examples https://i.stack.imgur.com/Npx5G.png ...

The design problem arises from using jQuery to dynamically prepare the table body at runtime

The table row and data are not appearing in the correct format. Here is a link to the problem on Fiddle: http://jsfiddle.net/otc056L9/ Below is the HTML code: <table border="1" style="width: 100%" class="eventtable"> <thead style="color: b ...

Creating a stunning image reveal animation using GSAP and clip-path within a React environment

When attempting to create an animation for revealing an image using GSAP and the clip-path property within a Component, I encountered an issue. The animation works perfectly when using the first clip-path value, but as soon as I switch to the other one, th ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Encountering an error code of 500 when executing the createIndex function in Pouch

I'm currently working on setting up a basic index, and I have the following code snippet: currentDB.createIndex({ index: { fields: ['name'] } }).then((result) => { }).catch((error) => { }) However, when I try to r ...

Django AJAX for implementing a unique Like button

I've been attempting to implement a like button using Ajax. In my strain model, I have a field called user_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='strains_liked', ...