Harshit Laddha
Harshit Laddha

Reputation: 2124

Javascript efficient approach for changing inner dom elements of a list item

I have a unordered list with 12 list items inside it

<ul class="rb-grid" id="list">
   <li class="view view-fifth">
       <div class="mask">
          <h2>Article Name</h2>
          <p>Brief</p>
          <a href="#" class="info">Read More</a>
       </div>
   </li>
   ...
   ...
</ul>

Now what i want is that on page load i have to change the content of these h2 and p tags, now while i can do this by hardcoding every list item, but can anyone tell me a better way to make all changes at once by using javascript or jquery anything.... Now i found something like this in dojo , this will make clear what i want actually -

var items = registry.byId("list").getChildren();
array.forEach(items, function(item, idx) {
item.onClick = function(evt) {
};
});

I want to do some such thing to change the contents of the h2 and the p tags inside every list items

Upvotes: 2

Views: 250

Answers (4)

Michael Geary
Michael Geary

Reputation: 28860

Here for comparison is a more idiomatic jQuery version of Mr_Green's answer:

$('.rb-grid').children('li').each( function( i, element ) {
    var $element = $(element);
    $element.find('p').html("change to something");
    $element.find('h2').html("change to something");
});

OTOH, you may not even need the loop, depending on what you're doing. If you just want to change all the relevant nested p and h2 elements to the same value, then Tushar Gupta's answer is a simpler way to do it.

Upvotes: 1

chris-l
chris-l

Reputation: 2841

A non jquery way:

var ee = document.getElementById('list').getElementsByTagName('li');

for(i=0; i<ee.length; i++) {
    ee[i].getElementsByTagName('h2')[0].textContent = "hello world";
    ee[i].getElementsByTagName('p')[0].textContent = "article 2";
}

EDIT: It seems IE previous to IE9 does not have textContent and should use innerText instead. Thanks Mr_Green!

Upvotes: 2

js

var x =$('.rb-grid').children('li');
x.find('p').html('change to something');
x.find('h2').html('change to something');

Upvotes: 2

Mr_Green
Mr_Green

Reputation: 41832

Try this: (jquery)

var lis = $('.rb-grid').children('li');
for(var i = 0; i < lis.length : i++){
    $(lis).eq(i).find('p').html("change to something");
    $(lis).eq(i).find('h2').html("change to something");
}

Upvotes: 2

Related Questions