Search code examples
javascriptandroidjqueryhtmlintel-xdk

I am developing and XDK app. Any correction with this code


How can I select a paragraph contents in HTML using javascript such that I can apply a onclick function? Here is my code : When I click on the paragraph it selects all the paragraphs in the document but i only want it to select individual paragraph content

<script> 
function social_share() { 
      var quote = $("p").text();                          
      window.plugins.socialsharing.share("Follow me on twitter.", quote, null,"url",function(result){  
            alert('result: ' + result); 
            }, function(result){ 
            alert('error: ' + result); }); 
 } 
</script>
Some data

another paragraph


Solution

  • This line:

    var quote = $("p").text();
    

    is selecting all the p elements (i.e. all the paragraphs), so text() from all p elements is all the text from all the paragraphs concatenated together. You need to specify the specific paragraph selected. There are a couple ways to do this.

    If you want to specify onclick in the HTML code, you could do this:

    <p onclick="social_share(this)">paragraph text</p>
    

    but generally this is considered bad style. Assuming you're using jQuery, a more fashionable solution might be to do this:

    <p class='clickable'>pagagraph text</p>
    . . .
    function init() {
        var pgraphs = $(".clickable");
        pgraphs.click( function() {
            social_share($(this).text());
        }
    }