最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Selecting <p> within a div using javascript - Stack Overflow

programmeradmin2浏览0评论

I want to select the p tag and style it within a content class div. Here is the example HTML:

<div class="content">
<p> this is paragraph </p>
</div>

I want to select and style the p which is immediately after the div. The p has no ID or class.

How can I select it via JavaScript?

I want to select the p tag and style it within a content class div. Here is the example HTML:

<div class="content">
<p> this is paragraph </p>
</div>

I want to select and style the p which is immediately after the div. The p has no ID or class.

How can I select it via JavaScript?

Share Improve this question edited Apr 20, 2014 at 16:18 user3536919 asked Apr 20, 2014 at 16:15 user3536919user3536919 1132 gold badges2 silver badges7 bronze badges 2
  • 1 divElement.getElementsByTagName('p'). – h2ooooooo Commented Apr 20, 2014 at 16:17
  • That <p> is not 'after' the <div>. – David Thomas Commented Apr 20, 2014 at 16:20
Add a comment  | 

4 Answers 4

Reset to default 9

This can be done using querySelector. You did not specify minimum browser requirement.

var p = document.querySelector(".content p");
p.style.color = "red";

http://jsfiddle.net/g35ec/

if you can get access to the div, you can use

var ps = divObject.getElementsByTagName('p'); //ps contains all of the p elements inside your div
var p = ps[0]; //take the first element

You can use querySelector

document.querySelector('.content p').style.color = 'red';

to style

tag use it normally as you do in the style tag or if you use a separate css file. Have a look at this fiddle it might help you

http://jsfiddle.net/3uUjf/

p{
background-color: cyan;

}

发布评论

评论列表(0)

  1. 暂无评论