Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting <p> within a div using javascript

Tags:

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?

like image 624
user3536919 Avatar asked Apr 20 '14 16:04

user3536919


People also ask

How do you select all p elements inside a DIV element?

Use the element element selector to select all elements inside another element.

Can you put P inside DIV?

In HTML 4, the DIV element cannot be inside another block-level element, like a P element. However, in HTML5 the DIV element can be found inside and can contain other flow content elements, like P and DIV.

How do I select a DIV element?

Use document.querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .

How do I select all p tags in HTML?

You select p tags by replacing div by p in the method call.


2 Answers

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/

like image 158
Jeff Avatar answered Oct 21 '22 03:10

Jeff


You can use querySelector

document.querySelector('.content p').style.color = 'red';
like image 29
adeneo Avatar answered Oct 21 '22 03:10

adeneo