Manipulate the contents of children divs within a parent div using JavaScript or JQuery

<div id="abc">
    <div id="a_b"> abcd </div>
    <div id="c_d"> xyz </div>
</div>

I have a challenge where the divs on my page are generated dynamically and their IDs change every time the page loads. When the window is loaded, I need to pass the content of a_b and c_d to a function func(), and then display the output within the same div. How can I access each child of div abc and update their content accordingly?

Answer №1

For the solution you are looking for, consider using .text() in combination with .each().

$(window).load(function(){
  $("#abc > div").each(function() {
     $(this).text(someFunction($(this).text()));
  });
});

Alternatively, a more efficient approach would be to utilize the callback function of .text(),

$(window).load(function(){
  $("#abc > div").text(function(_,v) {
    return someFunc(v);
  });
});

Answer №2

To easily access the #abc div at all times, you can target it first and then iterate over any direct child div elements using the text() method along with a handler function. Here's an example:

$('#abc > div').text(function(i, v) {
    return v + ' foobar';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc">
  <div id="a_b">abcd</div>
  <div id="c_d">xyz</div>
</div>

If you prefer, you can compile an array of the content within the child divs and then pass that to a custom function like func():

var textContents = $('#abc > div').map(function() {
    return $(this).text();
}).get();

func(textContents);

function func(arrText) {
    console.log(arrText); // = [ 'abcd', 'xyz' ]
}

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

Using regular expressions to validate input in Javascript

Seeking assistance to validate an input text using the pattern <some_string>:<some_string> in JS/JQuery. For instance: A110:B120 AB12C:B123 I understand this might seem overly simplistic, but any guidance would be greatly appreciated. ...

Using JSP and Jquery for uploading files

I have a specific requirement to submit a form asynchronously using AJAX, which includes a file input. Below is the code I have written, however, I am encountering an error. Input.jsp: <script> function fileUpload() { var formData = $('#myform ...

Issues with the functionality of the map method in Javascript arrays

I have integrated Laravel and Vue.js to develop a chat application. To secure my response in Laravel, I implemented encryption to prevent unauthorized access from the console: public function get() { $contacts = User::where('id', '!=&ap ...

Validating Captcha with jQuery and AJAX for Securimage

I have gone through numerous questions and tutorials, but no matter what I try, I can't seem to get it to work. Here is the HTML code for my login page (/login.php) <form action="func/login.php" method="post" name="login"> ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

How can I add a hyperlink to a Javascript string array?

I am currently facing a challenge in adding a hyperlink to a string using .link and .innerHTML methods. I believe there might be a misunderstanding on my part as I am quite new to this. Here is the code snippet I have been working with: <div id="type ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

What is the functionality of the protection against AngularJS JSON vulnerability?

When working with JSONs in Angular, it is recommended to prefix them with )]}'\n for added protection against potential JSON vulnerability: A JSON vulnerability could allow a third-party website to transform your JSON resource URL into a JSONP ...

The CSS file that is defined first in the node.js HTML is the only one being utilized

Currently, I am incorporating CSS and JS files into my node.js/express application with the help of the ejs templating engine. Interestingly, while the JavaScript files are being successfully implemented, only the first included CSS file seems to be affect ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Exploring the Touch Feature in Angular

I am facing an issue with touch events as I am not receiving any useful X/Y coordinates. The event object does not provide the necessary information I need for touch events (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). Despi ...

jQuery does not have the capability to automatically calculate Value Added Tax on form submissions

I have included this section in my form to calculate the value added tax (VAT): <div class="col-md-4"> <div class="form-check"> <input type="radio" id="vat_on" name="vat" value=&q ...

The periodLookup array does not have a defined value for periodStr. Why is this error being caught?

Here is a method that I am working with: set_period_help_text: function(periodInput){ var metric = MonitorMetric.getSelectedMetric(); var periodStr = $('select[name=metric_period]').val(); var datapoints = Number(periodIn ...

What could be causing the unexpected behavior of req.query in NEXT.js?

In the latest version of NextJS App Router, I have the following code located in the file app\api\products\route.tsx import { initMongoose } from "@/lib/mongoose"; import Product from "@/models/products"; import { NextApi ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...

Updating the input value of one field by typing into another field is not functioning properly when trying to do so for

I'm managing a website with a form that has three fields which can be duplicated on click. Here is an excerpt of my code: $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $("#niy"); var ...

Nodejs restricts the user from performing the action

Currently, I am utilizing Nodejs with Expressjs and encountering an issue when trying to run the project. The connection is established successfully but when attempting to access the URL (localhost:3001/api/plans), an error appears in the console: MongoSer ...

Is it possible to retrieve information from a MySQL database by utilizing Bootstrap and Ajax with the selected ID?

I am currently working on two php pages. The first php page contains a table with records that can be edited using a Bootstrap Modal, while the second php page processes updates to the MySQL database. Below is the code for the first php page (edit_account ...