简体   繁体   中英

How to split the text retrieved from `div` elements

I have this HTML:

<div class="chip">java<span class="material-icons close">×</span></div>
<div class="chip">spring<span class="material-icons close">×</span></div>
<div class="chip">python<span class="material-icons close">×</span></div>

With the following script I try to retrieve the texts without the x . I get the values of the div elements using their class name, but when passed to split it, the same string returns without any split:

var skills = $('.chip').text();
var arr = skills.split('x');
for(var i=0;i<arr.length;i++){
    alert(arr[i]);
}

For example:

var skills = 'javaxspringxpython';

The output remains the same. I know this is because of the .text() method, but not sure how to solve this. I tried using .val() , but that didn't work.

How can I resolve this?

Your HTML has already three separate elements.

Instead of splitting the combined text, you could get the individual contents of the tags, and kick out any other tags from that content (the span elements in your case). Then you will have three matching text nodes, which you then need to map to array items:

 var skills = $('.chip').contents().filter(function() { return this.nodeType === 3; // only immediate text in div, not in span }).map(function() { return $(this).text(); }).get(); console.log(skills); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="chip">java<span class="material-icons close">×</span></div> <div class="chip">spring<span class="material-icons close">×</span></div> <div class="chip">python<span class="material-icons close">×</span></div> 

Its Work For Me..

 $(document).ready(function() { var skills = $('.chip').text(); var arr = skills.split('x'); for(var i=0;i<arr.length;i++){ // alert(arr[i]); console.log(arr[i]); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='chip'>javaxspringxpython</div> 

Hope Its Work !!!

Happy Coding !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM