0
$(".unitHeading").click(function(){
    urls = this.id;
    heading = $(this).data("id");
    rendition.display(urls);
    classname = $('iframe').contents().text(heading).find('class');
    console.log(classname);
    return false;
});

I have an iframe file where I am going to find the class name with the help of text here text means heading. For example <p class="block_7">Hello World</p> through Hello World I need to fine class i.e block_7. How can I do this?

1
  • So basically you are trying to find an element via its content? Commented Jan 17, 2020 at 6:43

3 Answers 3

1

You can iterate over Iframe Contents and validate the text

let iframe = jQuery('iframe#frameId');
$(iframe[0].childNodes).each(function() {
     if($(this).text().includes('Hello World')){
       let el = $(this)[0].nodeValue;
       console.log($(el).attr('class'));
     }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<iframe id="frameId">
  <p class="block_7">Hello World</p>
</iframe>

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

1 Comment

I am trying @manikantgautam but nothing happen console error Uncaught TypeError: Cannot read property 'createDocumentFragment' of null
0

Use the :contains psuedo-selector:

const heading = 'Hello World';
const $iframe = $('<div><p class="block_7">Hello World</p></div>');
const match = $iframe.find(`p:contains('${heading}')`);
if (match.length) {
  console.log(match[0].className);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If any <p> elements containing that text are found, they'll be put into the match collection, and then you can look at the className of the <p>.

2 Comments

Actually I have only heading i.e Hello world and all <div><p class="block_7">Hello World</p></div> is a part of iframe. So, I need to find class name through only Hello World @CertainPerformance
What do you mean? From the iframe, all you need to do is .find(`p:contains('${heading}')`); - by concatenating the Hello World part with the :contains psuedo-selector, you can find the matching element (if there is one). All it's using is the Hello World and the iframe
0

You have to use :contains():

$('iframe').contents().find(`:contains('${heading}')`)[0].classList;

2 Comments

$('iframe').contents().find(:contains('${heading}')) what is it returns?
n.fn.init [prevObject: n.fn.init(1), context: document, selector: ":contains(Based on Structure)"]

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.