简体   繁体   中英

How do I get text from each span with a specific class tag?

I have a list of email addresses. Each of them is in a span like so: <span class="checked-emails-list">email@example.com</span> I need to get that email address and put it in an array of objects. Each object has 2 fields, the email address and a string. The string is preset and not important here.

I'm using an each loop in my javascript file to retrieve the span text, but I'm doing it incorrectly, as it just places "text" in the email field. What would be the correct way to retrieve the span text value?

var rowObject = {
  Email: '',
  ConfirmEmail: '',
  deleted: 'no'
}

var emailSubs = [];

$('.checked-emails-list span').each(function () {
  rowObject.Email = ($(this).text);
  rowObject.ConfirmEmail = ($(this).text);
  emailSubs.push(rowObject);
});

$(this).text() in jQuery, 'text' is a method. You are using like a property.

In Plain Javascript I would do something like this

var element = document.getElementsByClassName("checked-emails-list");
var result = [];
element.forEach(function(element){
  result.push(element.innerHTML);
});

.text is not function it should be text(). And another problem is that you are using rowObject object on each loop. It makes reference all time until you reinitialized it. you should reinitialize this object inside the loop

 var emailSubs = []; $('.checked-emails-list span').each(function () { let rowObject={ Email: $(this).text(), ConfirmEmail:$(this).text(), deleted: 'no' } emailSubs.push(rowObject); }); console.log(emailSubs);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='checked-emails-list'> <span>a</span> <span>b</span> <span>c</span> <span>d</span> </div>

$(document).ready(function(){

        var emailSubs = [];

        $('.checked-emails-list').each(function () {
           var obj = this

            emailSubs.push({
                Email: $(this).text(), 
                ConfirmEmail:$(this).text(),
                deleted: 'no'
            });
        });
        console.log(emailSubs.length)
})



<span class="checked-emails-list">email111@example.com</span><br/>
<span class="checked-emails-list">email2222@example.com</span><br/>
<span class="checked-emails-list">email3333@example.com</span><br/>

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