0

I have this piece of code:

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

I need to get the text from an element which is in that source code. For example, consider the page having an element like:

<a class="something">something goes here</a>

I need to get that text of class 'something' with JavaScript. The request.source returns the source code with structure as it is.

2
  • I'm sorry but why do you ask such a basic question that has thousands of answers in different flavours googlable/finadable in under 5 seconds? Commented Oct 21, 2015 at 15:11
  • 1
    Possible duplicate of How to get value by class name in JavaScript or jquery? Commented Oct 21, 2015 at 15:12

1 Answer 1

0

You should be able to turn the source code into jQuery object and use it like usual from there.

var requestedSource = request.source;
$(requestedSource).find('a.something').first().text();

This works for me in a very simple test on jsfiddle.

Note that you may have to play around with whatever $.find() returns if you have more than one anchor element with the class "something" (I just used $.first() to simplify my example). In that case, you can iterate through the results of $.find() like an array.

If that solution doesn't work, another (but worse) way you could do it would be to write the requested code to a hidden div, and then run $.find() from the div (though if the first solution doesn't work, there is likely something going wrong with request.source itself, so check its contents).

For example:

$('body').append('<div id="requestedSource" style="display: none;"></div>');

And then:

$("#requestedSource").append(request.source);
$("#requestedSource").find("a.something").first().text();

If you're repeating this request often, you can also empty the hidden div by calling $.empty() on it when you're done processing:

$("#requestedSource").empty();

For best performance, you would want to store everything in a variable and write once:

var hiddenRequestSource = '<div id="requestedSource" style="display: none;">';
hiddenRequestSource += request.source;
hiddenRequestSource += '</div>';

$('body').append(hiddenRequestSource);  

var myResults = $("#requestedSource").find("a.something").first().text();
$("#requestedSource").empty();
Sign up to request clarification or add additional context in comments.

1 Comment

This is a generic task that has lots of answers already. In order to avoid duplication and avoid feeding the "help vampires" who are too lazy to use search it's always better to link to a good existing topic which preferably has many answers.

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.