8

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?

2

4 Answers 4

10

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/

Sign up to request clarification or add additional context in comments.

Comments

7

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

2 Comments

my question is: i would like to select p inside div tag. and p is no id or class. how I can select p? could you explain more.. thank
@user3536919 - what browsers are you targeting? there are many options, but not all are compatible with older browsers.
5

You can use querySelector

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

5 Comments

Be aware that the querySelector method isn't compatible in IE7 and below.
@Hatsjoem - And getElementsByClassName is not available in IE8, so querySelector has better support
Is it not? I had no idea about that (beyond the usual 'poor IE support').
Nope, getElementsByClassName is IE9 and up only, while querySelector works in IE8 and above.
Even jQuery is dropping support for IE6/7 later this year, so I'd call compatibility issues from those browsers pretty irrelevant at this point.
1

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.