Reputation: 2077
New to jquery. I already got this running in javascript but am switching to jquery so I can use .each
. Is there some special rule preventing me from using JavaScripts .replace
inside jQuerys .each
?
var jse_sanitized_title = "";
var jse_article_title = "";
var jse_article_titles = $('.jse_article_title');
$.each(jse_article_titles, function(i) {
jse_article_title = jse_article_titles[i].innerHTML;
//error for this says jse_article_titles[i].replace is not a function
jse_sanitized_title = jse_article_titles[i].replace(/ /g,"_");
})
EDIT: The purpose of the replace is to replace spaces with underscores.
Upvotes: 0
Views: 129
Reputation: 7663
To do it the way you were trying (with innerHTML) you need to reference the node with get()...you'd need to do this:
jse_article_titles.get(i).innerHTML
However, you should be able to shorten that a bit.
$('.jse_article_title').each( function() {
$(this).html( $(this).html().replace(/ /g,"_") );
});
// or
$('.jse_article_title').each( function() {
this.innerHTML = this.innerHTML.replace(/ /g,"_");
});
// whichever floats your boat
[EDIT]: Sorry, I was wrong about needing .get(). jse_articles_titles[i] is perfectly valid as long as the number is not negative, which is unlikely.
Upvotes: 0
Reputation: 79830
EDIT: The purpose of the replace is to replace spaces with underscores.
Updated to use .text() function to set replace all spaces
with _
$('.jse_article_title').text(function () {
return this.innerHTML.replace(/ /g, '_');
});
May be you need
jse_sanitized_title = jse_article_title.replace(/ /g,"_");
//using the jse_article_title
or
jse_sanitized_title = jse_article_titles[i].innerHTML.replace(/ /g,"_");
or Using jQuery,
jse_sanitized_title = $(this).text().replace(/ /g, "_");
Upvotes: 1
Reputation: 150253
$.each(jse_article_titles, function() {
jse_article_title = this.innerHTML;
jse_sanitized_title = jse_article_title.replace(/ /g,"_");
});
After the update, it looks like you want to do something like this:
$('.jse_article_title').each(function(){
this.innerHTML = this.innerHTML.replace(/ /g,"_");
});
There is another way with jQuery:
$('.jse_article_title').html(function(index, old){
return old.innerHTML.replace(/ /g,"_");
});
Upvotes: 3
Reputation: 3862
Try this:
$.each(jse_article_titles, function() {
jse_article_title = $(this).html();
jse_sanitized_title = jse_article_title.replace(/ /g,"_");
})
Upvotes: 0
Reputation: 284786
Presumably you mean:
$.each(jse_article_titles, function(i) {
jse_article_title = jse_article_titles[i].innerHTML;
//error for this says jse_article_titles[i].replace is not a function
jse_sanitized_title = jse_article_title .replace(/ /g,"_");
jse_article_titles[i].innerHTML = jse_sanitized_title;
})
If you have not already declared jse_article_title
, put a var here, like:
var jse_article_title = jse_article_titles[i].innerHTML;
Note that you have to reassign it at the end. Finally, there are no special rules like this. jQuery is just a library.
Upvotes: 2