soren.qvist
soren.qvist

Reputation: 7416

Loop through name/values of an object to replace html in unique div's using jQuery

I'm using the following code:

  $.each($dataObj, function(index, value) {
    $(index).html(value); 
  });

Which of course does not work since $(index) is not a valid syntax.

Each index in the object corresponds to a a unique div-id on the webpage, so what I want to do is to replace the html in all of the div-id's listed in the dataObj with 'value'. How do I do that?

Upvotes: 1

Views: 255

Answers (2)

Alex Sexton
Alex Sexton

Reputation: 10451

You can use the $dataObj to access each.

Depending on it's contents, you might want:

$dataObj.eq(index).html(value);

However, it seems like you also might want to do an each loop like so:

$dataObj.each(function(i, value){
  $(this).html(value);
});

But even that's unnecessary if it's all the same value

$dataObj.html(value);

Would effectively loop through each element for you.

Upvotes: 1

Peter J
Peter J

Reputation: 57957

To make it valid jQuery syntax, simply add the 'ID' selector in front of it:

$.each($dataObj, function(index, value) {
  $('#' + index).html(value); 
});

Upvotes: 1

Related Questions