1xxooxx
1xxooxx

Reputation: 57

add class/id via javascript/jquery to div with specific text inside

Im trying to customize a specific page by injecting it with javascript/jQuery to add a css class/id to a specific "div" in the sidebar. I've copied and pasted the code on jsfiddle link. Im trying to ONLY add "nodisplay" class/id to the blue highlighted box (see screenshot here) so I can hide it via css.

I can NOT use the "nth-child" css selector because that blue box is sometimes displayed first, or sometimes displayed second, etc. I want to ADD "nodisplay" to the parent div ONLY IF the first child div contains text "Manage".

logic:

if div.SidebarList-sidebarListHeader-m1Kth contains text that matches exactly = "Manage",
then add "nodisplay" to parent div css;

Upvotes: 0

Views: 394

Answers (5)

mitmak
mitmak

Reputation: 96

The .closest() function is the immediate parent of element.

$("div.SidebarList-sidebarListHeader-m1Kth:contains('Manage')").closest("div").addClass("nodisplay");

Upvotes: 0

Abhilash Ravindran C K
Abhilash Ravindran C K

Reputation: 1856

Following code will works for you,

$('.SidebarList-sidebarListHeader-m1Kth').filter(function() {
    return $(this).text() == 'Manage';
}).parent('div').hide();

click here fiddle

Upvotes: 0

danish farhaj
danish farhaj

Reputation: 1354

I add code sample for you.

$('.SidebarList-sidebarListHeader-m1Kth:contains("Manage")').parent().addClass("nodisplay");

check here is your fiddle

Upvotes: 0

4b0
4b0

Reputation: 22323

Use contains to check desire text and use parent to find parent.

if ($(".menu:contains('Sed')")) {
  $('.menu').parent().addClass('dclass');
}
.dclass {
  background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>   
 <div class='menu'>
  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
  sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt
  ut labore et dolore magnam aliquam quaerat voluptatem
</div>
</div>

Upvotes: 1

yaakov
yaakov

Reputation: 4655

Use $("div:contains('my text')").closest('div'). See the jQuery :contains API and the jQuery .closest() API.

Upvotes: 0

Related Questions