Jimmyu
Jimmyu

Reputation: 21

Traversing DOM with jquery

If I have the following div tag...

<!doctype html>
<div id="idea">
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
</div>

In jquery, if i want to use the div id to change the last p tag and use the 2nd p element class to change Hello world! to something else. My efforts (which aren't working):

  $(document).ready(function) {
    $('#idea:last').html("something else");
  }
  $(document).ready(function) {
    $('.newsbanner[1]').html("something else");
  }

Upvotes: 0

Views: 105

Answers (2)

webbist
webbist

Reputation: 456

$('.news:nth-child(2)').html("something else");

Will change the second ".news" html

The example you tried with an array is incorrect. You need to declare the array first. have a read of nth-child recepies from css tricks, they can be useful to find elements in JS.

https://css-tricks.com/useful-nth-child-recipies/

Update:

// Selects using CSS selectors the second p element, .text() changed the 
// html elements content and .addClass() adds the class. 
$('#idea p:nth-child(2)').text('something else').addClass('someClass');
// Selects the last element
$('#idea p:last-of-type').text('something else');

https://jsfiddle.net/516crdLd/

Upvotes: 1

Jainil
Jainil

Reputation: 1496

You can use :nth-of-type() Selector. Check this document

Upvotes: 1

Related Questions