Get the title text from a selected div and create an array using JQuery

I'm attempting to gather the text from all divs' Title Attributes and store them in an array, but I'm having trouble finding the correct selection.

The title is important because it holds the specific string that I require.

Below are three divs with unique titles:

<div class = 'test' title='title1'>Hello</div>
<div class = 'test' title='title2'>goodbye</div>
<div class = 'test' title='title3'>farewell</div>

This is my current jQuery code:

$(document).ready(function() {

$array = $('[title][title!=]').each(function(){
  $(this).attr("title").makeArray;})

 alert($array)

});

The alert only displays [Object object]

In this example, I am aiming to create an array containing [Title1, Title2, Title3].

Any assistance on achieving this would be greatly appreciated.

********************************UPDATE************************************

Thank you, the initial solution worked perfectly. Your help is truly valued.

Answer №1

const titlesArray = $.map($('[data-title][data-title!=""]'), function(element) { return element.getAttribute('data-title') });

FIDDLE

Finds and stores all elements with a non-empty data title attribute into an array via mapping.

Answer №2

let myArray = []; // initialize an empty array and assign it to a variable outside of the current scope

$('.item').each(function() { // iterate through all elements with class 'item'
    let elementText = $(this).text(); // get the text content of the current element
    myArray.push(elementText); // add the text content to the array
});

console.log(myArray); // use this for testing purposes, remember to remove after verifying functionality

Answer №3

Here's a recommendation:

const headings = $('.example').map(function(){
    return this.heading;
}).get();

Check out these resources for more information:

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

Tips for configuring options within a jQuery widget factory using data retrieved from server-side variables stored in a JSON file

I am looking to configure the settings for a widget using JSON file variable values. How can I achieve this and how do I transfer the JSON file to the client side? The following code snippet is taken from the jQueryUI Widget Factory <script> $(f ...

How can I handle returning different types of Observables in my Angular application?

I can't seem to get an observable to return properly. The mergeMap function inside my code doesn't appear to be executing at all. Here are the relevant snippets of code: book.service.ts import {HttpClient, HttpHeaders} from '@angular/comm ...

Zurb Foundation's sections have a strange issue where navigating between them introduces unexpected whitespace

I'm feeling frustrated as I try to work with Zurb Foundation sections. I've updated to the latest version 4.3.1. Following the documentation provided here: but encountering strange behavior while navigating through results. Refer to the screen ...

Utilizing jQuery's Chained Selectors: Implementing Selectors on Previously Filtered Elements

DO NOT MISS: http://jsfiddle.net/gulcoza/9cVFT/1/ LATEST FIDDLE: http://jsfiddle.net/gulcoza/9cVFT/4/ All the code can be found in the above fiddle, but I will also explain it here: HTML <ul> <li id="e1">1</li> <li id="e2" ...

The margin property in jQuery does not seem to be functioning properly when trying to send

Within the view page, there is jQuery code that sets a margin on a div. Below is the code: <script type='text/javascript'> $('#someID').css('margin-left', '10px'); </script> This code functions proper ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

Viewing the JSON value within a select tag using Zend Framework 2

My approach involves fetching data from a database: public function getAllProjectDomain() { $dbadapter = $this->adapter; $sql = new Sql($dbadapter); $select = $sql->select(); $select->columns(array('cmain&ap ...

Is there a way to limit the width of the input box once it reaches a specific pixel measurement?

One issue I'm facing involves the following code snippet: <html> <head> <script type="text/javascript"> function Expand(obj){ if (!obj.savesize) obj.savesize=obj.size; obj.size=Math.max(obj.savesize,obj.v ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Determine the dimensions of the objects within a JSON array

My JSON response creation looks like this : { "G5LDUHRPEEA6B-39CFBWYA": [], "JMSK0DKOEEA0UXMY750O3W": [], "ISVN8JF1EEAD3W398ZNOSA": [ { "delloData": "1478644629", "ref": "75", "dataType": "String", "somePart": LA, ...

Remove element in array[x] removes the value without deleting the entire element

I encountered an issue with an object that contains duplicate values. To address this, I tried using delete new_object[1] to remove the value. However, upon checking the console, the object 0800 displayed "undefined". ["293", undefined, "298", "297"] ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

Choose all items on each page with Material-UI's table pagination

Can items be selected solely on the current page or per page within the Table? Check out this demo for reference. ...

Activate the Alert (https://material-ui.com/components/alert/#alert) starting from the React component at the bottom of the hierarchy

When it comes to alerts, a normal alert is typically used like alert("message to be displayed");. However, I prefer using material UI Alerts which return a JSX component. For example: <Alert severity="success">This is a success alert — check it out ...

Retrieving information from a JSON reply within an Angular 2 service

I am currently utilizing a service in angular 2 that retrieves JSON data from an API (). The code for fetching the data is depicted below: getImages() { return this.http.get(`${this.Url}`) .toPromise() .then(response => response.json() ...

When generating dynamic text boxes, a new area is always allocated for each new set of dynamic text boxes that are created

<html> <head> <script src="jquery-1.10.2.min.js"></script> <script> function AddingTextBoxes() { var NumOfText=$("#NumOfTextBoxes").val(); $('#NewlyCreatedSe ...

What steps should I take to ensure that the array yields the correct output?

Why is my code not creating an array of [0, 1, 2] when I pass the number 3 as a parameter? const array = [0]; const increment = (num) => { if (num > 0) { increment(num - 1); array.push(num); } return; }; console.log(array); incremen ...

The jQuery script fails to function properly within dynamically loaded content via ajax

After browsing through various articles and seeking help from Google, I've managed to do some basic coding as a designer. However, there's a complex problem that I'm struggling with. On my main page, I have news displayed and when scrolling ...

Having trouble loading the React app when using the @mui/styles package

After downloading a package from the MUI website, I encountered an error when trying to import "@mui/styles" which is resulting in browser errors. The package was downloaded from this source: https://mui.com/system/styles/basics/ Upon running my React app ...