Reputation: 123
I have a list like this
<ul class="example">
<li>
<span class="type"></span>
<a href="#">New document.txt</a>
</li>
<li>
<span class="type"></span>
<a href="#">Another document.zip</a>
</li>
</ul>
How can I get the text after "." and insert to "type"? The result should be like this
<ul class="example">
<li>
<span class="type">txt</span>
<a href="#">New document.txt</a>
</li>
<li>
<span class="type">zip</span>
<a href="#">Another document.zip</a>
</li>
</ul>
Upvotes: 1
Views: 180
Reputation: 115212
Iterate over the span and update the text content with the text after the dot(.
) in the adjacent sibling.
// use text method with callback to iterate and update
// based on the returned value
$('.example .type').text(function() {
return $(this)
// get the a tag
.next()
// get text content
.text()
// split the text
.split('.')
// get the last element from array
.pop();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="example">
<li>
<span class="type"></span>
<a href="#">New document.txt</a>
</li>
<li>
<span class="type"></span>
<a href="#">Another document.zip</a>
</li>
</ul>
Upvotes: 6