Awanti
Awanti

Reputation: 109

How to wrap the element with matching button text?

Hi i am trying to append the div to the button with the corresponding to that button text

(i.e. In the case of below example the button text is "Download" so i am appending the div class as new and if the button text is "Upload" i will append some other div class).

And for the appending div I am using wrap API.

Here is my code

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
  <button class="btn" title="run">Download</button>
  <script>
    $(document).ready(function() {
      var buttontext = $("button").text();
      alert(buttontext);
      $('button[text="Download"]').wrap("<div class='new'></div>");
    });
  </script>
</body>

</html>

I am trying to get the button text like this button[text="Download"] but it is not working.

Finally i want the output something like this

<div class="new">
  <button class="btn" title="run">Download</button>
</div>

Any help will be appreciated.

Upvotes: 0

Views: 40

Answers (1)

Eric G
Eric G

Reputation: 2617

You could user jquery's contains method:

$(document).ready(function() {
  $('button:contains("Download")').wrap("<div class='new'></div>");
});

Here is a working codepen:

http://codepen.io/egerrard/pen/MJpwdz

And the documentation on contains:

https://api.jquery.com/jQuery.contains

Upvotes: 2

Related Questions