What is the best way to substitute one element with a different one?

Here is my HTML snippet:

<html>
    <head></head>
    <javascript>
        var item = document.getElementById('demo');
        console.log(item);

        var myList = document.getElementsByClassName('myClass');
        for (var i=0; i<myList.length; i++) {
             console.log(myList[i]);
        }
    </script>

    <body>
        <section>
            <div class="needs_update">placeholder</div>
        </section>
    </body>
</html>

In addition, I have a variable that contains some JavaScript code:

let content = "document.querySelector('.selector').innerHTML = 'New Content'";

I want to replace the existing content inside the div with the class name needs_update using the value from the JavaScript variable. How should I approach this?

The desired output after replacing should be:

<html>
    <head></head>
    <body>
        <section>
            document.querySelector('.selector').innerHTML = 'New Content';
        </section>
    </body>
</html>

Answer №1

If you're using jQuery, the code to achieve this would look like:

var content = "<h1>Heading</h1><p>Some text</p>";
$(".target_element").parent().html(content);

Alternatively, without jQuery:

document.getElementsByClassName('target_element')[0].parentNode.innerHTML = content;

Answer №2

If you want to replace content using jQuery, you can utilize the replaceWith function.

$('.should_be_replaced').replaceWith(str);

var str = "<b>title</b><p>sth <span>sss</span></p>";
$('.should_be_replaced').replaceWith(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <head></head>
    <body>
        <section>
            <div class="should_be_replaced">something</div>
        </section>
    </body>
</html>

If you prefer to achieve the same result without using jQuery, you can do so with vanilla JavaScript.

document.querySelector('.should_be_replaced').outerHTML = str;

var str = "<b>title</b><p>sth <span>sss</span></p>";
document.querySelector('.should_be_replaced').outerHTML = str;
<html>
    <head></head>
    <body>
        <section>
            <div class="should_be_replaced">something</div>
        </section>
    </body>
</html>

Answer №3

To update the content, you have the option to utilize the direct HTML method.

var text = "<h1>Heading</h1><p>Some text <span>more text</span></p>";
    jQuery("article").html(text);

http://jsfiddle.net/abc123xyz/

Answer №4

All you need to do is use jQuery for this task.

let container = jQuery('container');
container.find('element').remove();
container.html(content);

Answer №5

Give this a shot:

<html>
    <head></head>
    <body>
        <section>
            <div id="replace_me" onclick="trigger()">placeholder content</div>
        </section>
     <script>
        function trigger() {
            var content = "<b>suggested title</b><p>example text <span>more text</span></p>";
            document.getElementById("replace_me").innerHTML = content;
        }
     </script>
    </body>
</html>

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

Proper method for handling ajax response without relying on the success handler

Similar Question: How can I make a jQuery AJAX request synchronous? Waiting for an Ajax response Let me explain my perspective. I have a good grasp on this particular code snippet. $.getJSON(someURL, function(data){ //do something with the re ...

Can News be generated without the need to add a new _id in Mongoose?

Whenever I attempt to make revisions to my document, a problem arises. Upon creating a new object, an error is thrown indicating that my current field already contains an _id field. let freshArticle = new News({ title: "title" ...

The imported package in Node.js cannot be located

I'm encountering an issue when trying to deploy my project on the server. Everything runs smoothly on my PC with no import problems. Thank you for your assistance! Error Message: Error [ERR_MODULE_NOT_FOUND]: Module '/home/igor/backend/alina_edu ...

Steps for creating a login form that redirects to a website

Looking to improve the HTML code (reviewing changes) Still learning how to create a website, so there might be errors in the code. I'm using neocities.org as the platform. I tried customizing the HTML source but struggling with removing the white sp ...

Encountered error: "Node.js and socket.io: Address already in use"

Experimenting with chat using Node.js and socket.io Currently, I am running Ubuntu 12.04 as a user and have a folder "pp" on my desktop. In this folder, I have placed a server file named server.js. Below is the client code: $(document).ready(function() ...

Displaying Hierarchical Data with AngularJS and ng-repeat

Recently, I've been working on finding an elegant solution to represent hierarchical data in my application. Specifically, I have implemented a slide effect for bootstrap badges that showcase sub-categories using AngularJS. With some guidance from th ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

Customizing the add row functionality in material table

Before the add row in the editable table opens, I would like to run a function. https://i.sstatic.net/7kVVL.png It is important for me to execute a specific function before this user interface becomes visible. (such as console.log('Hello')) Here ...

Error message saying "AuglarFire Authentication failing due to unrecognized provider with routers"

Recently, I've been exploring the Firebase documentation on authentication with Routers. In my project, I'm using Ionic with ui-router, incorporating abstract views and actual views with controllers. Here's the structure I have set up: .sta ...

Setting the default date in JQuery datepicker and using multiple datepickers

Currently, I am utilizing a datepicker tool which can be found at this link. In the HTML form that I have, there are two date fields. My goal is to have the first field default to today's date and the second field default to today's date minus 7 ...

Return the outcome of an Axios POST request

Upon integrating JWT verifyToken into my non-JWT api call, my Axios POST request now returns an empty result set. Function 2 (/userget) is functioning correctly and displays results on HTML, whereas Function 7 (/api/userget) can retrieve data and token but ...

The jQuery function for navigating back does not immediately trigger

I currently have a jQuery function that should make the assigned link act as a "Go back to previous page" link: function goback() { $('a').click(function(){ parent.history.back(); return false; }); } However, it only works w ...

"Learn the best way to showcase images within Pusher's real-time chat application

Having trouble displaying images in real-time chat using Pusher. I am storing the images as BLOB but cannot display them on the client side using JavaScript. When the person who sends the message types, the image shows up fine, but on the receiver's s ...

The initial selection in my dropdown menu is highlighted

I am attempting to create a CSS dropdown menu for the first time. I have encountered some issues along the way. The dropdown menu appears correctly with a red background color, but the first item displays a different background image instead of the red bac ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

Sending Dual Parameters to PHP File Using AJAX

Currently, I am facing an issue where I can successfully pass one value to a Bootstrap modal via AJAX, but my code stops working when I try to pass a second value. JavaScript function claimOrder(str, stre){ if (str=="") { document.getElementById("txtH"). ...

Before the custom font finishes loading, useEffect is triggered

Custom font usage in my app: @font-face { font-family: "Koulen"; src: url("./assets/fonts/Koulen-Regular.ttf") format("truetype"); } body { font-family: "Koulen"; } An issue arises as the useEffect is called ...

The Drupal-7 website encountered an AJAX HTTP error: HTTP response code 200

Running a clean Drupal installation, I have encountered a minor issue while running a simple program. A popup appears on the browser displaying: An AJAX HTTP error occurred I haven't installed many modules, just views and ctools on top of the basi ...

Having trouble retrieving the text of an element using Selenium

Looking at the DOM element provided: <span class="styles__Content-rlm06o-1 ixoRjG">20.00000000</span> I am attempting to extract the value 20.00000000 using the following Python code: text = driver.find_elements_by_xpath("//*[@c ...

I'm looking for a solution to implement a vertical carousel in Google's Materialize CSS without the need for custom development

Looking to create a unique vertical scrolling "carousel" using Google's Materialize CSS library. I have a good understanding of the steps required to construct a carousel. # haml %ul.carousel %li.carousel-item Some Content %li.carousel-item ...