Jack Barham
Jack Barham

Reputation: 3219

Get data from attribute and use it to replace other text

I'm building a legend - When the user clicks on an icon I want to grab the data from the "data-title" attribute and then use that text to replace the "p.map-legend-key__copy" which currently says "Marker text".

Here is my code so far...

HTML:

<div class="map-legend">
    <ul class="map-legend-list cf">
        <li class="map-legend-list__item legend-1" data-title="legend one"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-2" data-title="legend two"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-3" data-title="legend three"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-4" data-title="legend four"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-5" data-title="legend five"><i class="fa fa-map-marker"></i></li>
    </ul>
    <div class="map-legend-key">
        <p class="map-legend-key__copy">Marker text</p>
    </div>
</div><!-- map-legend -->

jQuery:

$('.map-legend-list__item').click(function() {
    var legendText = $(this).attr('data-title');
    $('p.map-legend-key__copy').replace('Marker text', legendText);
});

Thnaks, Jack.

Upvotes: 0

Views: 87

Answers (2)

reyaner
reyaner

Reputation: 2819

this could be an other way:

var legendText = $(this).data('title');
$(".p.map-legend-key__copy").html(function(i,t){
    return t.replace('Marker text', legendText)
});

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25882

There should be

var legendText = $(this).data('title');

If you want to replace whole text

$('p.map-legend-key__copy').text(legendText);

If you want to replace just Marker text

$('p.map-legend-key__copy').text($('p.map-legend-key__copy').text().replace('Marker text', legendText));

Upvotes: 2

Related Questions