With this HTML:
<h1>This is my <img src="https://dummyimage.com/100x50/000/fff&text=BIG" alt="BIG"> title</h1>
In Chrome or Firefox, if I select the rendered text and copy it (Ctrl-C), I’ll get
This is my BIG title
(the alt
text of the image is included in the copied text)
Can I achieve the same using jQuery? $('h1').text()
gives me only This is my title
(without BIG
).
I know I can get the alt
text itself with $('h1').attr('alt')
but how do I insert it at the correct position in the .text()
string?
3
Answers
The quick and dirty way to do it would be to get every image and insert text before or after it, then reverse after your .text() call
You could try to save the created text nodes in a JQuery or other Object so that after your text call you could remove them all. Alternatively, you could iterate through your imgs again and do
Basically I pass on all the nodes (not elements) of the designated element. If type=3 then it’s text. Otherwise I assume it’s an image and take the
alt
attribute. It’s also possible to make a recursion if the element isdiv
for example. Update: made it recursive.You could try something like this using jQuery methods.