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 para开发者_运维问答graph</p>
<script>
$('li').add('p').css('background-color', 'red');
</script>
$('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.
jQuery 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)
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');
精彩评论