user3536919
user3536919

Reputation: 113

Selecting <p> within a div using 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?

Upvotes: 7

Views: 21206

Answers (4)

Knight Rider
Knight Rider

Reputation: 188

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;

}

Upvotes: 1

Jeff
Jeff

Reputation: 12173

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/

Upvotes: 9

attila
attila

Reputation: 2219

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

Upvotes: 6

adeneo
adeneo

Reputation: 318232

You can use querySelector

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

Upvotes: 5

Related Questions