tags:

views:

40

answers:

3

Hi folks. Why all elements turn red? I only intend to turn <p> red.

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
</ul>
<p>a paragraph</p>

<script>
$('li').add('p').css('background-color', 'red');
</script>
+1  A: 

jQury chains events, what you have said here is For each li add a p and make it red.

$('li').add('p');
$('li p').css(''background-color', 'red');

Should work =0)

Dale Hurley
.add doesn't add elements to the dom believe it or not, .add actually just adds elements to the array of selected dom items. so this actually says give me all the li's, add all the p's, and then make them red in the background.
nathan gonzalez
Yes sorry it is append =)
Dale Hurley
+4  A: 

$('li') is selection all the li
$('li').add('p') is adding p tag into selected all the li
$('li').add('p').css('background-color', 'red') is changing all the li and p backgroundColor to red.

from jQuery.add API

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

Soe Moe
.add doesn't add elements to the dom believe it or not, .add actually just adds elements to the array of selected dom items. so this actually says give me all the li's, add all the p's, and then make them red in the background
nathan gonzalez
+1  A: 

this actually says give me all the li's, add all the p's, and then make them red in the background. if you just want the p tag to be red, do this:

('p').css('background-color', 'red');
nathan gonzalez