Is it possible for me to display a particular section of a webpage by utilizing document.getElementById(href)?

Is it possible to retrieve a specific part of a content page to display in a popup box?

Let's say we have a page called "content page" with the following structure:

<body>

<p id="part1">Tread ... inch. </p>

<p id="part2">Tread ... inch. </p>

<p id="part3">Tread ... inch.</p>

</body>

And on another page, we have some JavaScript code for a popup box as shown here:

<head>
<script type="text/javascript" src="popupBox.js"></script>
</head>
<body>

Show content of part one: <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
Show content of part two: <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
Show content of part three: <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.

</body>

Now, in the popup.js file, can we target a specific ID from the href of the clicked link?

var href = an.href; 
var boxdiv = document.getElementById(href).getElementById("Show The content of this ID tag!"); 

Any thoughts or suggestions?

Answer №1

Your request brings to mind the functionality of WML, where multiple cards are displayed on a single page but only one at a time. While you can load content from one page into another, it may not be in the exact way you are picturing.

The getElementById function specifically retrieves elements based on their ID attribute and nothing else. To display parts of another page as needed, you would first need to load its content.

Within popupBox.js:

var show_hide_box;
# Setting width, height, and border early is done for simplicity
(function(width, height, border) {
    var pages = {};

    function show_hide_box(link) {
        var path = (/^[^#]*/.exec(link.href))[0];
        if (pages[path]) {
            show_content(pages[path], link);
        } else {
            fetch_content(link, path);
        }
        return false;
    }

    function show_content(path, link) {
        var id = (/#(.*)/.exec(link.href))[1];
        if (content[id]) {
            # Display content[id], which is a DOM node
            ...
        } else {
            # The page exists, but not the fragment. Could search 
            # content.elements for the 
            ...
        }
    }

    function fetch_content(link, path) {
        $.ajax({
            url: link.href,
            success: function(data, textStatus, jqXHR) {
              pages[path] = {elements: $(data).filter('p')};
              pages[path].elements.each(function (idx, elt){
                  # TODO: handle elements w/ no id
                  pages[path][elt.id] = elt;
              });
              show_hide_box(link);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                # Can't load the content, so just load the page.
                window.location.href = link.href;
            }
        );
    }

    window.show_hide_box = show_hide_box;
})(400,400,'2px solid');

$(function() {
    $('.external_content').click(function(evt) {
        show_hide_box(this);
        evt.preventDefault();
    });
});

In the other page:

<body>
  Show content of <a href="TreadDepth.html#part1" class="external_content">part one</a>.
  Show content of <a href="TreadDepth.html#part2" class="external_content">part two</a>.
  Show content of <a href="TreadDepth.html#part3" class="external_content">part three</a>.
</body>

It is generally recommended to assign event listeners in a script rather than inline in HTML. Additionally, avoid using generic phrases like "click here" for linking text.

Answer №2

It seems like you're looking to display the content of a specific URL in a box or container on your website.

There are a couple of ways you can accomplish this. Here are two suggestions:

  • The recommended method is to load the content using ajax. This link will take you to the jQuery Ajax Documentation, which can simplify the process for you)
  • Another option is to utilize iFrames.

Answer №3

Sorry, but it's just not going to work out.

After reviewing the code, I managed to track down the original website where it was published.
The link:

If you take a look at the three links provided on that page, you'll notice that each one leads to a different destination.

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

Is there a way to toggle the visibility of a textarea with a button using knockout and the foreach binding?

Knockout is new to me and I have encountered an issue. I am trying to create a button and textarea for each project, with the textarea initially hidden on page load. When the button is clicked, it should toggle the visibility of the corresponding textarea. ...

Waiting for file changes in JavaScript using AJAX

Currently, I am in the process of developing a website to manage my Raspberry Pi robot. Through a .py script called GPS.py, I am able to control two stepper motors by executing the following command: sudo ./GPS.py forward 100 30 The first argument specif ...

Display the json encoded result of a MySQL SUM() query

I am attempting to use JSON to print the total sum of a price. Here is my current approach: $query="SELECT SUM(cost) FROM `Service`"; $result = mysql_query($query); $json = array(); while($row = mysql_fetch_array($result)) { $json[&a ...

Explain the concept of declaring a variable and then retrieving a component using an arrow

I'm looking to define a variable within the iteration of a .map() function while also returning a component. However, I've encountered an error when trying to have this variable inside the map. Is this even possible and if so, how would I go abo ...

Iterate over various selection lists and tally the frequency of each option being chosen

I am currently working on a website that requires multiple instances of the same select-option to be created. I want to keep track of how many times each option is selected, and save that count as a variable to be used in a PHP email function. For instanc ...

Leveraging HTML Page Variables in Google Tag Manager for Enhanced Merchant Code Integration

I'm currently in the process of incorporating Google Merchant Code via GTM on a product checkout/thank you page. The Google Merchant code is : <script> window.renderOptIn = function() { window.gapi.load('surveyoptin', function() { ...

Enhance your Angular2 Directive

Looking to customize the angular2-clipboard npm package by extending its functionalities. Specifically, I aim to access and modify its ngOnInit() function to cater to a specific copying use case. Being new to angular2, I am uncertain about the process of ...

Best practices for integrating JavaScript with PHP and MySQL

When it comes to inserting data into a MySQL database from JavaScript, I typically use AJAX with jQuery's $.POST function and PHP's mysqli function. This allows me to send the data to a PHP script which then inserts it into the database. Here is ...

Mean stack authentication issue: missing token

Overview: Currently, I'm in the process of developing an application that utilizes node/express for the backend, mongo as the database, and angular for the frontend. User authentication is handled through jsonwebtoken, where a token is stored in local ...

Maintain the button in an enabled state until it is clicked once more

I have a question that I hope you can help me with. I have an HTML input tag with a button type that triggers a JavaScript onclick function. The functionality is working as expected, but now I want to enhance it by keeping the button in an active state aft ...

Alter the texture or hue in the mesh surface

I am faced with a challenge involving a Three.Geometry object that contains multiple vertices and faces forming a grid. My goal is to dynamically alter the color or material of a selected face. geometry.colorsNeedUpdate = true; geometry.faces[1].color.se ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Error encountered when initializing NextJS Firebase Authentication App

I'm encountering challenges with implementing Firebase authentication using Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection to Firebase. However, I'm running into an issue whe ...

Is there a way to execute a JavaScript file within another JavaScript file?

I'm in the process of developing a text-based game through the console, utilizing an NPM package known as "prompts" to prompt the user for input. One specific question it asks is, "What OS do you want to run?" and returns the selection as JSON data. F ...

Accessing variables within the controller's scope

Here is the JSON data I'm working with: { "id": "026001", "description": "Drop Forged Double Coupler", "CASHCUST01": { "hireRate": "0.01500", "saleRate": "2.50000" }, "SMITH00010": { "hireRate": "0.02500", "saleRate": "1.50000" }, " ...

When viewing an array, the objects' values are displayed clearly; however, when attempting to access a specific value, it

I am attempting to retrieve the board_id of my objects in the columnsServer array... columnsServer: Column[]; this.service.getColumns() .subscribe(data => { this.columnsServer = data; console.log(this.columnsServer); for (this.i = 0; this.i ...

Adjust the transparency and viewability of an object loaded from OBJMTL Loader using three.js dat-gui

I have successfully loaded an object using OBJMTLLoader and now I want to be able to manipulate its position, visibility, and opacity using the dat-gui control panel. Although I have been able to move the loaded object following this example, I am having t ...

Determining the quantity of displays

Can we detect the number of screens in use using JavaScript or jQuery? We are working on an application that should not be displayed on multiple screens, even if the hardware allows for it. Appreciate any assistance with this matter. Thank you. ...

Issues with JS events on the WooCommerce cart page are causing functionality to be disrupted

Currently, I have implemented a script to convert numbers to different formats using jQuery: jQuery(document).ready( function(){ jQuery( 'body' ) .on( 'update_checkout updated_checkout updated_cart_totals', function() { ...

Can you help me transform this javascript code into a JSON format?

Is there a way for me to organize my data so that I have one main question with 5 choices, each associated with a vote? It's like thinking of it as a tree where the question is the root and has 5 leaves, representing the choices, and each choice furth ...