Search code examples
javascriptjquerygoogle-chrome-extensionjavascript-objectsdom-events

Get elements from source code stored in variable


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.


Solution

  • 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();