3

What I'm trying to do is is find an elements from all the child elements within my parent element (el) that have a certain class and a certain text. I just want the div

This works $(el).children().find("div") and finds all the children

So I want the div with inner text "hello" with a class of "selected"

$(el).children().find("div").text("hello").hasClass("selected");

The line above doesn't do anything or has some were side effect of changing all this child elements text to something random.

I am def NOT a jquery expert and can't seem to find the right combination of selectors to get the job done

1
  • hasClass returns true/false Jul 4, 2017 at 9:45

2 Answers 2

5

Using class selector and contains together, this should do

  var childs =   $(el).find("div.selected:contains('hello')");
1
  • Oh man, I was soooo close. I tried .find() but could not get it to work. Thanks loads for your help. Just what I needed
    – djack109
    Jul 4, 2017 at 9:59
0

Your syntax is a little off. Firstly you can use find() alone without calling children() first, hasClass returns a boolean not a jQuery object, and text() is used to set a value, not find an element.

To do what you require you should put the class on the selector in the find() call, then use :contains to search for the element with the relevant text content. Try this:

$(el).find("div.selected:contains('hello')")

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.