1

I have a link with a text, a linebreak and a image inside.

<a title="title" href="#" class="mail">[email protected]
  <br><img src="img/icons/icon.png">
</a>

So to get all together inside the anchor I use:

$('.mail').html();

Now I want to exclude this only to get [email protected]:

<br><img src="img/icons/icon.png">

Example

$('.mail').html();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a title="title" href="#" class="mail">[email protected]
   <br><img src="img/icons/icon.png">
</a>

How should I do this?

3 Answers 3

5

You can use text() to get just the text for the <a> tag

var text = $('.mail').text();
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a title="title" href="#" class="mail">[email protected]
   <br><img src="img/icons/icon.png">
</a>

2
  • As allways Master Yoda tells the truth. Thank you this works.
    – Achim Udo
    Commented Dec 12, 2017 at 11:39
  • Always two there are, no more, no less. A master and an apprentice. :) Commented Dec 12, 2017 at 11:44
3

In this specific case, if you just want the text, use text instead of html (perhaps with .trim() or $.trim(...)):

console.log($('.mail').text().trim());
<a title="title" href="#" class="mail">[email protected]
   <br><img src="img/icons/icon.png">
</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In the general case, though, if there are elements you want to include and others you want to exclude in this kind of situation, you can make a clone and remove them:

console.log(
  $('.mail').clone()
    .find("br, img").remove()
    .end()
    .html()
);
<a title="title" href="#" class="mail">[email protected]
   <br><img src="img/icons/icon.png">
   <span>Suppose you wanted this span but not the <code>br<code> or <code>img</code>.</span>
</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2

Use .text() instead of .html()

$('.mail').text();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a title="title" href="#" class="mail">[email protected]
   <br><img src="img/icons/icon.png">
</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.