Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, and is versatile enough for future additions...

<div class="col">
    <a href="http://google.com">Google</a>
</div>

<div class="col">
    <a href="http://yahoo.com">Yahoo!</a>
</div>

<div class="col">
    <a href="http://facebook.com">Facebook</a>
</div>

<div class="col">
    <a href="http://twitter.com">Twitter</a>
</div>

The desired result is...

<div class="col">
    <a href="http://google.com">Google</a>
    <span>http://google.com</span>
</div>

<div class="col">
    <a href="http://yahoo.com">Yahoo!</a>
    <span>http://yahoo.com</span>
</div>

<div class="col">
    <a href="http://facebook.com">Facebook</a>
    <span>http://facebook.com</span>
</div>

<div class="col">
    <a href="http://twitter.com">Twitter</a>
    <span>http://twitter.com</span>
</div>

Any suggestions are welcome!

Answer №1

It seems like you haven't given it a go at writing the code yourself. It's important to try tackling this on your own.

$('.col a').each(function() {
    var $this = $(this);
    $("<span>"+$this.attr('href')+"</span>").insertAfter($this);
});

Answer №2

$('section.box').each(function(){
  console.log($(this).find("a").attr("href"));
  //Find the solution on your own
});

Answer №3

$('.col > a').append(function() { 
    return $('<span>', {text:this.href});
});

Answer №4

Here is a solution that should work for you. Utilize the each function and learn more about selectors.

$(document).ready(function(){
   $("div.col").each(function(){
      var hreftext = $(this).find("a").attr("href"); 
      $(this).append("<span>" + hreftext + "</span>");
   });

}); ​

Answer №5

Here's a potential solution:

$('div.col').each(function() {
    var $link = $(this).find('a:first'),
        address = $link.attr('href');
    $('<span>').text(address).insertAfter($link);
});

Answer №6

$(".col").each(function(){
 var link = $(this).find("a");       
 $("<span/>",{text:link.attr('href')}).insertAfter(link);
 });

View Demo

Answer №7

You can achieve this easily using a simple jQuery 'append()' method

Check out this example on JsFiddle

$('div.col').each(function(){
        var link = $(this).children('a:first').attr('href');
        $(this).append('<span>' + link + '</span>');
    });

Answer №8

I agree with the solutions provided. It might be more efficient to cache your selector instead of having jQuery search the DOM each time, especially for larger lists where performance could be impacted.

var col = $('.col a');
col.each(function(){
  var val = $(this).text();
  $(this).append("<span>"+val);
})​

http://jsfiddle.net/cXkqc/2/

Update

I made a mistake in understanding the question initially. Here is the updated code and link.

 var col = $('.col a');
   col.each(function(){
   var val = $(this).attr('href');
   $(this).after("<span>"+val);
 })​

http://jsfiddle.net/cXkqc/3/

Special thanks to @am not i am

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

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Python Selenium returning 'None' when attempting to retrieve the source attribute of an image

Having trouble retrieving the src of images in the class "KfFlO" using selenium. Whenever I try to print for the source, Python keeps returning "none." Can anyone help me identify the problem? Below is my code snippet: from selenium import webdriver from s ...

How can I combine jQuery UI Themeroller with my own custom jQuery UI widget?

I am reaping the advantages of Themeroller in conjunction with the standard widgets provided by jQuery UI. The part that perplexes me is integrating Themeroller with a custom widget built on top of the jQuery UI widget factory. This excerpt from the help ...

Gather a variety of data inputs from a <select> tag and store them in a String array

Within my spring application, there is an html form that includes a select element which needs to pass values to the server. The code in the JSP page responsible for sending these values to the server is as follows: HTML Form <form name="form_lista_h ...

Why isn't Bootstrap validation functioning properly in my Modal?

I am attempting to implement client-side validation using bootstrap, as outlined here: https://getbootstrap.com/docs/4.0/components/forms/#custom-styles The challenge I'm facing is that my form is within a modal. When I click the submit button, nothi ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

Only render the div content in jQuery when the user has made a selection

Looking to optimize my website by incorporating tabs with a large amount of HTML content without slowing down the page load. Is there a way to use jQuery to load the div content only when each tab is selected? The basic structure of the HTML code would be ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Having trouble with button alignment in the header with Bootstrap 3?

Using Bootstrap 3 and looking to adjust the alignment of a star icon with the title in my HTML page. Here is the current setup: <p class="pull-right visible-xs"> <h3><center>2000 Cadillac Eldorado Esc (Prospect heights) $3500 ...

The v-on:click event handler is not functioning as expected in Vue.js

I am currently learning vue.js and facing some challenges. Below is the code snippet from my HTML page: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net ...

Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio... showFooter(){ return h / w > 1.2 || h > 560; } ...and ...

What is the best way to ensure the options/choices div reaches its ideal width?

Check out my StackBlitz project that I've set up In the styles.css file, you'll notice that I defined a fixed width of 650px for the option dropdown div, which is currently working fine @import '~bootstrap/dist/css/bootstrap.min.css'; ...

The error message "Trying to call zmq.zmqVersion as a function, but it's not a function" occured while attempting to import the ZeroMQ

My current project involves creating a react app that can subscribe to an IPC socket using JavaScript code. I chose to use npx create-react-app for this purpose. To handle the subscription, I decided to utilize the npm package zeromq. However, when instal ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Issue with navigation links on HTML website not functioning as expected

I would like the dropdown menu items to be clickable. For example: Menu item: Services Sub items: - branding } These already have working links - marketing } However, when I try to replace '#' with a link for Services, it d ...

Generate a table containing information organized by category

I am looking to create a component Table that groups countries together. Here is my mockup: enter image description here I am struggling to find a solution for this issue. Can someone please assist me? ...