Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting <p> within a div using jQuery

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

<div class="itemize">
    <p> Order Summery</p>
    <div>
        <p><strong>Packages:</strong> </p> <!-- i want to select this P tag-->
        <p><strong>Date:</strong> </p>
        <p><strong>Style:</strong> </p>
    </div>
</div>

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

How can I select it via jQuery?

like image 398
Mossawir Ahmed Avatar asked Jun 18 '12 06:06

Mossawir Ahmed


People also ask

Can you put P in 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.

What does div P Select in jQuery?

Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.

How do I select a specific tag in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I select a specific paragraph in jQuery?

If you're stuck with that structure, you're looking for nextUntil , which adds following elements up until (and not including) an element matching the selector you pass it: var n = 2; $("p:contains(Page " + n + ")"). nextUntil("p:contains(Page " + (n + 1) + ")"). css('background-color', 'red');


3 Answers

var test = $('.itemize')​.find('div:first')​.find(​'p:first')​​​.html();
alert(test);
​

Try here: http://jsfiddle.net/arvind07/H8vwA/

like image 197
Arvind Bhardwaj Avatar answered Oct 28 '22 12:10

Arvind Bhardwaj


You can do this way:

$('.itemize > div > p:eq(0)')

.itemize > div goes till:

<div class="itemize">
    <p> Order Summery</p>
</div>

And

.itemize > div > p:eq(0)

<div class="itemize">
    <p> Order Summery</p>
    <div>
        <p><strong>Packages:</strong> </p>
    </div>
</div>

The > allows to target direct children whereas eq(index) is used to get first p that you want.

like image 21
Sarfraz Avatar answered Oct 28 '22 12:10

Sarfraz


$('.itemize div p:first').html()

Check this link: http://jsfiddle.net/QJTYx/

If you want to add class to that p tag:

$('.itemize div p:first').addClass('selected');
like image 43
VibhaJ Avatar answered Oct 28 '22 13:10

VibhaJ