Guide on transferring the data of a jQuery variable to a different variable

How can I assign the content of a variable to another variable successfully? Here is what I have tried so far:

var className = $($(this).attr("class"););

$('.content').html(className)

EDIT:

Let's assume that the end value for "var className = $($(this).attr("class"););" is point1

point 1 contains:

EDIT 2: (CONTAINS FULL CODE)

    <div class="content"><h1>testing hello world</h1><div class="position"> <div class="point1"> test<br> awewa<br> TEST <h1> test </h1> </div></div></div>

    <script type="text/javascript">
    var point1 = '<div class="content"><h1>testing hello world</h1><div class="position"> <div class="point1"> test<br> awewa<br> TEST <h1> test </h1> </div></div></div>';
    var className = "Broken";
    $('.content [class] [class]').click(function () {$(this).fadeTo(250, 0.25, function () {
    className = $(this).attr("class");
    $('.content').html(className)

    $(this).fadeTo(250, 1.00);

    });}
    );

    </script> 


var point1 = '<div class="content"><h1>testing hello world</h1><div class="position"> <div class="point1"> test<br> awewa<br> TEST <h1> test </h1> </div></div></div>';

"$('.content').html(className)" needs to contain the string in point1 classname

Answer №1

Alright, let me explain it clearly. You have some HTML content stored in variables with the same names as class names of specific elements. When one of those elements is clicked, you want to retrieve the HTML from that variable and set it as the content of another element with the class name .content.

$('.someClass').on('click',function(){
    var className = this.className; // Get the classname which is a variable
   var content = window[className];
   if(content)
    $('.content').html(content); //Assuming the variable is defined in the window Scope. 
});

Breaking it down:-

window[className] <-- to access the variable defined in the window scope.

Update:-

For your updated code, try this approach. Since you are replacing the content and need the click event to work again, consider using a delegated event handler with .on(), or use .live for older versions of jQuery.

   var className = "Broken";
   $(document).on('click', '.content [class] [class]', function () {
       $(this).fadeTo(250, 0.25, function () {
           className = this.className;
           $('.content').html(window[className]);
           $(this).fadeTo(250, 1.00);

       });
   });

Check out the Demo here

Answer №2

Suppose 'this' represents an element (such as when you're inside a $.each() callback, then $(this).attr('class') will give you all the CSS classes assigned to that particular element. This doesn't include all the CSS rules affecting it, just what appears in the 'class=""'. The outer $() function here will conceal the return value from the initial assignment in your query. The second line is setting the innerHTML of an element with the class "content" to the value returned by the first line.

Answer №3

Revision:

Seems like you're aiming to achieve this:

let classSelected = $('.' + $(this).attr("class")).html();
$('.content').html(classSelected);

Answer №4

There seems to be a minor syntax error in the code, but overall it appears to be correct.

If you intend to display the value of the class property of the current element within the .content element, you can use the following code:

var className = $(this).attr("class");
$('.content').html(className)

Check out the demo: Fiddle

Update:
If className is a property associated with an object x, you can fetch the value using x[className]. If it's a variable in the global context, use window[className] instead.

var point1 = '<div class="content"><h1>testing hello world</h1><div class="position"> <div class="point1"> test<br> awewa<br> TEST <h1> test </h1> </div></div></div>';
jQuery(function($){
    var className = "Broken";
    $('.content').on('click', '[class] [class]', function () {
        $(this).fadeTo(250, 0.25, function () {
            className = $(this).attr("class");
            $('.content').html(window[className])
        });
    });
});

Updated Demo: Fiddle

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

Display text when hovering over a button

My goal is to achieve something similar to the following: <button class="addMore">+</button> I want to create an effect like this: when the button is hovered over. I have searched for different solutions, but none of them match the exact be ...

Position the SVG next to the link text in a Bootstrap navbar brand

I am using the .navbar-brand class from Bootstrap to include an SVG in my navbar. However, I want to display text next to the SVG and align it properly. The SVG and text are currently in the navbar but they are not aligned correctly. Below is the code snip ...

Add various inputs to a table using JavaScript

I came across a situation where I needed to append lines into a table in a specific way. However, I encountered an issue with JavaScript not accepting any input type='text' for an unknown reason. When I used a normal text variable, it worked fine ...

Using jquery to create HTML elements but unable to remove them using jquery

I'm facing an issue with removing newly created li elements in an unordered list using jQuery. The delete button works perfectly fine for the existing li, but not for the ones added dynamically. <!DOCTYPE html> <html lang="en> <head> ...

Troubleshooting PHP echo response issue with AJAX POST and FormData submission

Apologies for the inadequate title, I struggled to come up with a suitable one. Currently, I am working on a web-based platform for movies and anime, where users can contribute to the database by logging in and submitting forms. This project is my first i ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

How can I keep the CSS3 animation playing even after the hover state ends?

When hovering over the small menu logo on my site, there's a subtle wiggle effect that I really like. However, I would prefer if the animation played all the way through before repeating. Here's the code I'm currently using: Here is my code ...

Troubleshooting CSS compatibility issues in Firefox browser (or HTML rendering as plain text)

In a unique web page comparing two photos, the clicked one changes, but there's an issue in Firefox where HTML displays as text and links don't work. CODE:- * { box-sizing: border-box; } html { height: 100%; } body { height: 100%; mar ...

What is the best way to showcase a banner on a website to alert the user who is currently logged in about a new message waiting for them?

My current project involves enhancing the features of an existing ASP.net Form Application. User authentication is required during login. One of the new requirements is to display a special message to users when they log in, indicating that they have new ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

Introducing whitespace nowrap disrupts the CSS grid layout

I've encountered an issue with a grid layout featuring 2 columns. I'm trying to insert an element into one of the columns that will display an ellipsis if its content is too long. However, when I add whitespace: nowrap; to the CSS, it causes the ...

What is the best way to transition a div from the top to the bottom in mobile view?

Currently, I am utilizing Bootstrap 4 framework; however, if it operates effectively on version 3, then it should work seamlessly on v4. Within a single column, I have incorporated 2 div elements as follows: <div class="row"> <div class="col ...

Deselect a selected radio button by clicking on it

I am trying to create a radio button with an unchecked value, and I thought this code would work: $('form').on('click', 'input[type="radio"]:checked', function (event) { $(this).prop("checked", false); }); It seems simpl ...

Adjusting the width of tabs dynamically using jQuery

It's important to note that this question doesn't mirror the one found here. I am utilizing the jQuery UI Tab feature on my page and aiming for the tabs to occupy the entire width of the page. However, the number of tabs can vary between 0, 1, 2, ...

Adaptive design that uses identical HTML for both desktop and mobile versions

I'm currently working on a project using Bootstrap 4 to create a responsive design, but I'm facing some challenges. I managed to achieve the desired layout on CodePen, but I'm struggling to find a way to avoid repeating the code for both de ...

Avoiding repeated execution of event handlers in subviews of Backbone

Working with Backbone, I have a list container view that should house multiple section views with event handling. However, the issue is that the event is triggered as many times as there are subviews inside the container. I understand that moving the clos ...

How can you implement a delete button in jQuery DataTables using an API?

Is there a way to incorporate the delete button using the jQuery DataTables API? I have successfully installed the DataTable but am facing challenges in implementing the necessary methods. Any assistance would be greatly appreciated. Thank you! Visit thi ...

What is the best way to obtain the profile picture of a user on Instagram?

Can anyone provide guidance on how to implement code for fetching a post picture, similar to the profile picture functionality I have already working? (For example: ) function getPhoto(a) { // validation for instagram usernames var regex = new RegEx ...

We have encountered an issue with the syntax in the code: ajaxsample/update_agenda. It seems to be an unrecognized expression according to

Here's the code for updating my controller: public function update_agenda() { $id= $this->input->post('did'); $this->load->model('agenda_model'); $data = array ( ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...