Reputation: 7318
Usually when I want to get the text content of a class i just use a selector that will scan the entire dom.
Problem is that in my context I don't want it to scan the entire dom but a specific portion of html that I have cached in a variable with a jquery selector:
let searchHtml = $( "#search-results > p" )
Now, from lodash I need to iterate each of the elements in searchHtml and extract text of those with a class "link-title":
_.each( searchHtml, function( value, key ) {
const linkTitle = $( value[".link-title"] ).text() // HERE
}
how to properly format this code so linkTitle in the loop will correctly grab text from element with class "link-title" ?
Upvotes: 0
Views: 39
Reputation: 32354
Use find()
to get all the elements with a class of .link-title
, use jquery each()
to loop through them, use a array to save the text for each item found
searchHtml.find(".link-title").each(function(){
linkTitle.push($(this).text());
console.log($(this).text());
})
Upvotes: 1
Reputation: 133423
You can use .each()
no need of lodash
. Here .find()
is used to target descendants link-title
element after that .text()
can be used
let searchHtml = $( "#search-results > p" )
searchHtml.find(".link-title").each(function(index, element){
const linkTitle = $(element).text(); //Native code "element.textContent;"
});
Upvotes: 0